package com.useeinfo.oa.modules.maintaining.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.*;
import com.useeinfo.oa.common.config.ConstantKeyFilePath;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.CommonUtils;
import com.useeinfo.oa.common.utils.NumberUtil;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.enums.AuditTypeEnum;
import com.useeinfo.oa.modules.base.enums.MessageTypeEnum;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.base.vo.MessageVO;
import com.useeinfo.oa.modules.inspection.entity.InspectionWorkContentRemark;
import com.useeinfo.oa.modules.inspection.entity.InspectionWorkLog;
import com.useeinfo.oa.modules.maintaining.dao.MaintainOrderDao;
import com.useeinfo.oa.modules.maintaining.entity.*;
import com.useeinfo.oa.modules.maintaining.enums.*;
import com.useeinfo.oa.modules.repair.biz.RepairLevelBiz;
import com.useeinfo.oa.modules.repair.biz.RepairOrderBiz;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemAuthorityBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.biz.UserDeviceBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.entity.UserDevice;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.threadUtil.ThreadUtils;
import com.xiaoleilu.hutool.util.CollectionUtil;
import javafx.geometry.Pos;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Auther: xudong.sun
 * @Date: 2019/1/2 15:35
 * @Description:
 */
@Service("maintainOrderBiz")
public class MaintainOrderBiz extends CrudBiz<MaintainOrderDao, MaintainOrder> {

    @Autowired
    private MaintainOrderLogBiz maintainOrderLogBiz;
    @Autowired
    private FacilityMaintainSnapBiz facilityMaintainSnapBiz;
    @Autowired
    private MaintainOrderWorkContentBiz maintainOrderWorkContentBiz;
    @Autowired
    private ResourceBiz resourceBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private AuditFlowBiz auditFlowBiz;
    @Autowired
    private FacilityMaintainBiz facilityMaintainBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private MaintainTechnologyBiz maintainTechnologyBiz;
    @Autowired
    private MaintainDataBiz maintainDataBiz;
    @Autowired
    private PlanExecuteTimeBiz planExecuteTimeBiz;
    @Autowired
    private MaintainPartnerBiz maintainPartnerBiz;
    @Autowired
    private DictInfoBiz dictInfoBiz;
    @Autowired
    private AuditOrderBiz auditOrderBiz;
    @Autowired
    private ApplyOrderBiz applyOrderBiz;
    @Autowired
    private SystemUserOrganizationBiz systemUserOrganizationBiz;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private SystemAuthorityBiz systemAuthorityBiz;
    @Autowired
    private MaintainFocusBiz maintainFocusBiz;
    @Autowired
    private WorkContentRemarkBiz workContentRemarkBiz;
    @Autowired
    private MaintainToRepairBiz maintainToRepairBiz;
    @Autowired
    private MessageBiz messageBiz;
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private WorkingHoursBiz workingHoursBiz;
    @Autowired
    private PlanMessageSendBiz planMessageSendBiz;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private UserDeviceBiz userDeviceBiz;
    @Autowired
    private MaintainWorkLogBiz maintainWorkLogBiz;
    @Autowired
    private ApplicationModuleBiz applicationModuleBiz;
    @Autowired
    private RepairLevelBiz repairLevelBiz;
    @Autowired
    private RepairOrderBiz repairOrderBiz;

    public List<Object> getYearPlan(String id) {
        return dao.getYearPlan(id);
    }

    public String dashBoardInfo(String enterpriseId, String status, String date) {
        return dao.dashBoardInfo(enterpriseId, status, date);
    }

    public JSONArray getbetween(String enterpriseId, String start, String end, int type, boolean completed) {
        return dao.getbetween(enterpriseId, start, end, type, completed);
    }

    public List<Object> getOrganizationReceiveNum(String organizationId, String start, String end) {
        return dao.getOrganizationReceiveNum(organizationId, start, end);
    }

    public String maintainReportNum(String enterpriseId, String status) {
        return dao.maintainReportNum(enterpriseId, status);
    }

    /**
     * 按计划产生维保工单接口
     *
     * @param plannerOrder 工单计划
     * @param startTime    工单开始时间
     * @param endTime      工单结束时间
     * @return
     */
    public ResultDto makeMaintainOrder(PlannerOrder plannerOrder, Date startTime, Date endTime, int type, PlanExecuteTime planExecuteTime) {
        if (null == startTime || null == endTime || null == plannerOrder) {
            logger.info("未传入正确生成维保工单的参数");
            return ResultUtil.error("未传入正确生成维保工单的参数");
        }
        /*********改变状态，下次不再生成该工单**************/
        if (type == 1) {
            planExecuteTime.setStatus(1);
            planExecuteTimeBiz.addOrUpdate(planExecuteTime);
        }
        /*********生成工单基础信息start**************/
        MaintainOrder maintainOrder = new MaintainOrder();
        maintainOrder.setCreateDate(new Date());
        maintainOrder.setPlannerOrder(plannerOrder);
        maintainOrder.setOrderCode(plannerOrder.getEnterprise() == null ? StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6) : plannerOrder.getEnterprise().getId() + "-" + StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6));
        maintainOrder.setEnterprise(plannerOrder.getEnterprise());
        maintainOrder.setStartDateTime(startTime);
        maintainOrder.setEndDateTime(endTime);
        maintainOrder.setDelayRealTime(endTime);
        maintainOrder.setAssign(plannerOrder.getAssign());
        List<Long> ids = new ArrayList<>();
        Set<Position> positionSet = new HashSet<>();
        for (Position position : plannerOrder.getAssignPositions()) {
            ids.add(position.getId());
            positionSet.add(position);
        }
        maintainOrder.setAssignPositions(positionSet);
        Set<SystemUser> systemUserSet = new HashSet<>();
        for (SystemUser systemUser : plannerOrder.getAssignUsers()) {
            ids.add(systemUser.getId());
            systemUserSet.add(systemUser);
        }
        maintainOrder.setAssignUsers(systemUserSet);
        maintainOrder.setOrderAssignTypeEnum(plannerOrder.getOrderAssignTypeEnum());
        maintainOrder.setOrderName(plannerOrder.getName());
        maintainOrder.setCreateUser(plannerOrder.getCreateUser());
        maintainOrder.setAuditCompleteID(plannerOrder.getAuditComplete() == null ? null : plannerOrder.getAuditComplete().getId());
        maintainOrder.setCompleteFlow(plannerOrder.getCompleteFlow());
        maintainOrder.setDelayFlowID(plannerOrder.getAuditDelay() == null ? null : plannerOrder.getAuditDelay().getId());
        maintainOrder.setDelayFlow(plannerOrder.getDelayFlow());

        maintainOrder.setCancelFlowID(plannerOrder.getAuditCancel() == null ? null : plannerOrder.getAuditCancel().getId());
        maintainOrder.setCancelFlow(plannerOrder.getCancelFlow());

        maintainOrder.setRemindTime(plannerOrder.getRemindTime());
        maintainOrder.setRemindDateTime(StringConverters.beforeDate(startTime, plannerOrder.getRemindTime()));
        maintainOrder.setRequired(plannerOrder.getRequired());
        maintainOrder.setType(plannerOrder.getType());
        maintainOrder.setDegree(plannerOrder.getDegree());
        maintainOrder.setPoints(plannerOrder.getPoints());
        maintainOrder.setSafeInstruction(plannerOrder.getSafeInstruction());
        maintainOrder.setResource(plannerOrder.getResource());
        maintainOrder.setBelongOganization(plannerOrder.getOrganization());
        dao.add(maintainOrder);
        /*********生成工单基础信息end**************/

        /*********生成工单——设备和工艺——工作内容信息start**************/
        QueryParam queryParam = new QueryParam(-1, -1);
        queryParam.getSqlMap().put("plannerId", plannerOrder.getId().toString());
        queryParam.getSqlMap().put("maintainId", "is not null");
        List<FacilityMaintain> facilityMaintainSet = facilityMaintainBiz.findList(queryParam); /*plannerOrder.getFacilityMaintains();*/
        for (FacilityMaintain facilityMaintain : facilityMaintainSet) {
            FacilityMaintainSnap facilityMaintainSnap = new FacilityMaintainSnap();
            facilityMaintainSnap.setCreateDate(new Date());
            facilityMaintainSnap.setMaintainOrder(maintainOrder);
            facilityMaintainSnap.setOrderCode(maintainOrder.getOrderCode());
            facilityMaintainSnap.setAreaId(facilityMaintain.getAreaId());
            facilityMaintainSnap.setAreaName(facilityMaintain.getAreaName());
            facilityMaintainSnap.setFacilityCatId(facilityMaintain.getFacilityCatId());
            facilityMaintainSnap.setFacilityCatName(facilityMaintain.getFacilityCatName());
            facilityMaintainSnap.setFacilityCode(facilityMaintain.getFacilityCode());
            facilityMaintainSnap.setFacilityGroupCode(facilityMaintain.getFacilityGroupCode());
            facilityMaintainSnap.setFacilityGroupId(facilityMaintain.getFacilityGroupId());
            facilityMaintainSnap.setFacilityGroupName(facilityMaintain.getFacilityGroupName());
            facilityMaintainSnap.setFacilityId(facilityMaintain.getFacilityId());
            facilityMaintainSnap.setFacilityName(facilityMaintain.getFacilityName());
            facilityMaintainSnap.setMaintainId(facilityMaintain.getMaintainId());
            facilityMaintainSnap.setMaintainName(facilityMaintain.getMaintainName());
            facilityMaintainSnap.setQRCode(facilityMaintain.getQRCode());
            facilityMaintainSnap.setSpec(facilityMaintain.getSpec());
            facilityMaintainSnap.setTempVal(facilityMaintain.getTempVal());
            facilityMaintainSnapBiz.addOrUpdate(facilityMaintainSnap);

            /**解析工艺内容start***/
            JSONArray jsonArray = JSONArray.parseArray(facilityMaintain.getMaintainDataContent());
            for (Object object : jsonArray) {
                JSONObject jsonObject = (JSONObject) object;
                MaintainOrderWorkContent maintainOrderWorkContent = new MaintainOrderWorkContent();
                maintainOrderWorkContent.setCreateDate(new Date());
                maintainOrderWorkContent.setFacilityMaintainSnap(facilityMaintainSnap);
                maintainOrderWorkContent.setName(jsonObject.getString("name"));
                maintainOrderWorkContent.setMaxNumber(jsonObject.getDouble("maxNumber"));
                maintainOrderWorkContent.setMinNumber(jsonObject.getDouble("minNumber"));
                maintainOrderWorkContent.setPhoto(StringConverters.null2Boolean(jsonObject.getBoolean("photo")));
                maintainOrderWorkContent.setApplication_scenarios_id(jsonObject.getLong("applicationScenariosId"));
                maintainOrderWorkContent.setApplication_scenarios_name(jsonObject.getString("applicationScenariosName"));
                maintainOrderWorkContent.setContent(jsonObject.getString("content"));
                maintainOrderWorkContent.setResourceIds(jsonObject.getString("resourceIds"));
                maintainOrderWorkContent.setUnit(jsonObject.getString("unit"));
                maintainOrderWorkContent.setCategory(jsonObject.getString("category"));
                maintainOrderWorkContent.setInputTypeEnum(InputTypeEnum.valueOf(jsonObject.getString("inputTypeEnumCode")));
                maintainOrderWorkContentBiz.addOrUpdate(maintainOrderWorkContent);
            }
            /**解析工艺内容end***/
        }
        /*********生成工单——设备和工艺——工作内容信息end**************/

        //更新预计工时
        maintainOrder.setExpectWorkingHours(updateExpectWorkingHours(maintainOrder.getId() + ""));
        this.addOrUpdate(maintainOrder);

        //操作日志
        MaintainOrderLog maintainOrderLog = new MaintainOrderLog();
        maintainOrderLog.setMaintainOrder(maintainOrder);
        maintainOrderLog.setEnterprise(plannerOrder.getEnterprise());
        maintainOrderLog.setSystemUser(plannerOrder.getCreateUser());
        maintainOrderLog.setUserName(plannerOrder.getCreateUser() == null ? "" : plannerOrder.getCreateUser().getUserName());
        String detail = plannerOrder.getCreateUser().getUserName() + "在" + DateTimeUtils.formatDateToStringWithTime(new Date()) + ","
                + OrderOperationEnum.CREATE_ORDER.getName() + "，操作工单名称为：" + maintainOrder.getOrderName() + ",编号为：" + maintainOrder.getId();
        maintainOrderLog.setDetail(detail);
        maintainOrderLog.setOrderOperationEnum(OrderOperationEnum.CREATE_ORDER);

        //消息推送 TODO
        String content = "维保单:" + maintainOrder.getOrderCode() + "等待接单!";//消息内容
        ids = dao.maintainOrderUserIds(maintainOrder, maintainOrder.getEnterprise(), ids);//需要发送的人
        planMessageSendBiz.senMsg(maintainOrder.getId(), "maintain", maintainOrder.getEnterprise(), ids, content);

        return ResultUtil.success();
    }

    /**
     * 保存工单
     *
     * @return
     */
    public ResultDto save(MaintainOrder maintainOrder,
                          MultipartFile pic1,
                          String sImg1,
                          String end,
                          List<String> selectCompleteAuditFlowIds,
                          List<String> selectDelayAuditFlowIds,
                          List<String> selectCancelAuditFlowIds,
                          List<String> selectOrganizationIds,
                          HttpServletRequest request) {
        //先判断是否有绑定设备,并且设备是否都绑定了工艺
        if (StringUtils.isBlank(maintainOrder.getSerial())) {
            return ResultUtil.error("参数异常");
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("serial", maintainOrder.getSerial());
        List<FacilityMaintainSnap> facilityMaintainSnapList = facilityMaintainSnapBiz.findList(queryParam);
        if (CollectionUtils.isEmpty(facilityMaintainSnapList)) {
            return ResultUtil.error("请绑定设备");
        }
        for (FacilityMaintainSnap facilityMaintainSnap : facilityMaintainSnapList) {
            if (facilityMaintainSnap.getMaintainId() == null) {
                return ResultUtil.error("请绑定工艺");
            }
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        maintainOrder.setEnterprise(enterprise);
        maintainOrder.setCreateUser(systemUser);
        maintainOrder.setOrderStatusEnum(OrderStatusEnum.WAIT_TAKING);//未接单
        maintainOrder.setOrderCode(enterprise == null ? StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6) : enterprise.getId() + "-" + StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6));
        //上传资料操作
        if ("1".equals(sImg1)) {
            //首先删除之前的关联资料文件
            maintainOrder.setResource(null);
            //如果有新资料文件 再存新资料文件
            String savePath1 = FileUtils.fileUpload(pic1, ConstantKeyFilePath.MAINTAINING_SAFETY_PDF_DIR, ConstantKeyFilePath.MAINTAINING_SAFETY_PDF_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            if (StringUtils.isNotEmpty(savePath1)) {
                Resource resource = new Resource();
                String resourceName = pic1.getOriginalFilename();
                resource.setPath(savePath1);
                resource.setResourceTypeEnum(ResourceTypeEnum.PDF);
                resource.setResourceName(resourceName);
                resourceBiz.addOrUpdate(resource);
                maintainOrder.setResource(resource);
            }
        }
        Date startDate = DateTimeUtils.parse("yyyy-MM-dd HH:mm", DateTimeUtils.format(new Date(), "yyyy-MM-dd HH:mm"));
        maintainOrder.setStartDateTime(startDate);
        maintainOrder.setStartDateTime(startDate);
        maintainOrder.setEndDateTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm", end));
        maintainOrder.setDelayRealTime(maintainOrder.getEndDateTime());
        maintainOrder.setRemindDateTime(StringConverters.beforeDate(startDate, maintainOrder.getRemindTime()));
        if (CollectionUtils.isNotEmpty(selectCompleteAuditFlowIds)) {
            AuditFlow completeFlow = auditFlowBiz.findModel(StringConverters.ToLong(selectCompleteAuditFlowIds.get(0)));
            maintainOrder.setCompleteFlow(completeFlow.getFlow());
            maintainOrder.setAuditCompleteID(completeFlow.getId());
        } else {
            //默认审批流
            if (auditFlowBiz.getDefaultFlow("complete", enterprise, 2) != null) {
                maintainOrder.setCompleteFlow(auditFlowBiz.getDefaultFlow("complete", enterprise, 2).getFlow());
                maintainOrder.setAuditCompleteID(auditFlowBiz.getDefaultFlow("complete", enterprise, 2).getId());
            }
        }
        if (CollectionUtils.isNotEmpty(selectDelayAuditFlowIds)) {
            AuditFlow delayFlow = auditFlowBiz.findModel(StringConverters.ToLong(selectDelayAuditFlowIds.get(0)));
            maintainOrder.setDelayFlow(delayFlow.getFlow());
            maintainOrder.setDelayFlowID(delayFlow.getId());
        } else {
            //默认审批流

            if (auditFlowBiz.getDefaultFlow("delay", enterprise, 2) != null) {
                maintainOrder.setDelayFlow(auditFlowBiz.getDefaultFlow("delay", enterprise, 2).getFlow());
                maintainOrder.setDelayFlowID(auditFlowBiz.getDefaultFlow("delay", enterprise, 2).getId());
            }
        }

        if (CollectionUtils.isNotEmpty(selectCancelAuditFlowIds)) {
            AuditFlow cancelFlow = auditFlowBiz.findModel(StringConverters.ToLong(selectCancelAuditFlowIds.get(0)));
            maintainOrder.setCancelFlow(cancelFlow.getFlow());
            maintainOrder.setCancelFlowID(cancelFlow.getId());
        } else {
            //默认审批流
            if (auditFlowBiz.getDefaultFlow("cancel", enterprise, 2) != null) {
                maintainOrder.setCancelFlow(auditFlowBiz.getDefaultFlow("cancel", enterprise, 2).getFlow());
                maintainOrder.setCancelFlowID(auditFlowBiz.getDefaultFlow("cancel", enterprise, 2).getId());
            }
        }

        if (CollectionUtils.isNotEmpty(selectOrganizationIds)) {
            maintainOrder.setBelongOganization(organizationBiz.findModel(StringConverters.ToLong(selectOrganizationIds.get(0))));
        }
        maintainOrder.setOrderType(true);
        if (maintainOrder.getId() == null) {
            dao.add(maintainOrder);
        } else {
            dao.update(maintainOrder);
        }
        //给临时设备工艺信息添加id(正式绑定)
        for (FacilityMaintainSnap facilityMaintainSnap : facilityMaintainSnapList) {
            facilityMaintainSnap.setMaintainOrder(maintainOrder);
            facilityMaintainSnapBiz.addOrUpdate(facilityMaintainSnap);
        }
        //增加MaintainOrderWorkContent
        QueryParam queryParam1 = new QueryParam();
        queryParam1.getSqlMap().put("maintainOrderId", maintainOrder.getId() + "");
        queryParam1.getSqlMap().put("serial", maintainOrder.getSerial());
        List<FacilityMaintainSnap> facilityMaintainSnapList1 = facilityMaintainSnapBiz.findList(queryParam1);
        if (CollectionUtils.isNotEmpty(facilityMaintainSnapList1)) {
            for (FacilityMaintainSnap facilityMaintainSnap : facilityMaintainSnapList1) {
                MaintainTechnology maintainTechnology = maintainTechnologyBiz.findModel(facilityMaintainSnap.getMaintainId());
                if (maintainTechnology != null) {
                    QueryParam queryParam2 = new QueryParam();
                    queryParam2.getSqlMap().put("maintainTechnologyId", maintainTechnology.getId() + "");
                    List<MaintainData> maintainDataList = maintainDataBiz.findList(queryParam2);
                    for (MaintainData maintainData : maintainDataList) {
                        MaintainOrderWorkContent maintainOrderWorkContent = new MaintainOrderWorkContent();
                        maintainOrderWorkContent.setFacilityMaintainSnap(facilityMaintainSnap);
                        maintainOrderWorkContent.setName(maintainData.getName());
                        maintainOrderWorkContent.setCategory(maintainData.getCategory());
                        maintainOrderWorkContent.setApplication_scenarios_id(maintainData.getDictInfo().getId());
                        maintainOrderWorkContent.setApplication_scenarios_name(maintainData.getDictInfo().getPropertyName());
                        maintainOrderWorkContent.setInputTypeEnum(maintainData.getInputTypeEnum());
                        maintainOrderWorkContent.setMaxNumber(maintainData.getMaxNumber());
                        maintainOrderWorkContent.setMinNumber(maintainData.getMinNumber());
                        maintainOrderWorkContent.setUnit(maintainData.getUnit());
                        maintainOrderWorkContent.setPhoto(maintainData.getPhoto());
                        maintainOrderWorkContent.setContent(maintainData.getContent());
                        Set<Resource> pdfResource = maintainData.getEnclosure();
                        if (pdfResource != null && pdfResource.size() > 0) {
                            Resource resource = pdfResource.iterator().next();
                            if (resource != null) {
                                maintainOrderWorkContent.setResourceIds(resource.getId() + "");
                            }
                        }
                        maintainOrderWorkContentBiz.addOrUpdate(maintainOrderWorkContent);
                    }
                }
            }
        }
        //更新预计工时
        maintainOrder.setExpectWorkingHours(updateExpectWorkingHours(maintainOrder.getId() + ""));
        this.addOrUpdate(maintainOrder);
        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.CREATE_ORDER, request);

        //消息推送 TODO
        String content = "维保单:" + maintainOrder.getOrderCode() + "等待接单!";//消息内容
        List<Long> ids = new ArrayList<>();
        ids = dao.maintainOrderUserIds(maintainOrder, maintainOrder.getEnterprise(), ids);//需要发送的人
        planMessageSendBiz.senMsg(maintainOrder.getId(), "maintain", maintainOrder.getEnterprise(), ids, content);

        return ResultUtil.success();
    }

    /**
     * 设置截止日期
     *
     * @param id
     * @param endDate
     * @return
     */
    public ResultDto saveAssignDate(String id, String endDate, HttpServletRequest request) {
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(id));
        if (maintainOrder.getOrderStatusEnum().getCode().equals("WAIT_TAKING") || maintainOrder.getOrderStatusEnum().getCode().equals("WAIT_PULISHING")) {
            //在未接单之前都可以设置截止日期
            maintainOrder.setEndDateTime(StringConverters.ToDatePattern(endDate, "yyyy-MM-dd HH:mm"));
            maintainOrder.setDelayRealTime(StringConverters.ToDatePattern(endDate, "yyyy-MM-dd HH:mm"));
            dao.update(maintainOrder);
            //操作日志
            maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.END_DATE, request);
        }
        return ResultUtil.success();
    }

    /**
     * 指派人员
     *
     * @param assignIds
     * @param orderId
     * @return
     */
    public ResultDto assignUsers(String assignIds, String orderId, HttpServletRequest request) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(assignIds);
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(orderId));
        Set<SystemUser> systemUsers = maintainOrder.getAssignUsers();
        List<Long> ids = new ArrayList<>();
        if (systemUsers == null) {
            systemUsers = new HashSet<>();
        }
        for (Object id : jsonArray) {
            SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(id));
            if (systemUser != null) {
                systemUsers.add(systemUser);
                ids.add(systemUser.getId());
            }
        }
        maintainOrder.setAssign(Boolean.TRUE);
        maintainOrder.setOrderAssignTypeEnum(OrderAssignTypeEnum.USER);
        maintainOrder.setAssignUsers(systemUsers);
        dao.update(maintainOrder);

        //消息推送 TODO 推送给新的指派人员
        String content = "维保单:" + maintainOrder.getOrderCode() + "等待接单!";
        planMessageSendBiz.senMsg(maintainOrder.getId(), "maintain", maintainOrder.getEnterprise(), ids, content);

        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.ASSIGN_USER, request);
        return ResultUtil.success();
    }


    /**
     * 指派人员APP
     *
     * @param assignIds
     * @param orderId
     * @return
     */
    public ResultDto assignUsersApp(String assignIds, String orderId, HttpServletRequest request) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(assignIds);
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(orderId));
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        Set<SystemUser> systemUsers = new HashSet<>();
        List<Long> ids = new ArrayList<>();
        for (Object id : jsonArray) {
            SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(id));
            if (systemUser != null) {
                systemUsers.add(systemUser);
                ids.add(systemUser.getId());
            }
        }
        maintainOrder.setAssign(Boolean.TRUE);
        maintainOrder.setOrderAssignTypeEnum(OrderAssignTypeEnum.USER);
        maintainOrder.setAssignUsers(systemUsers);
        dao.update(maintainOrder);
        //消息推送 TODO 推送给新的岗位人员
        String content = "维保单:" + maintainOrder.getOrderCode() + "等待接单!";
        planMessageSendBiz.senMsg(maintainOrder.getId(), "maintain", maintainOrder.getEnterprise(), ids, content);
        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.ASSIGN_USER, request);
        return ResultUtil.success();
    }

    /**
     * 指派岗位
     *
     * @param assignIds
     * @param orderId
     * @return
     */
    public ResultDto assignPositions(String assignIds, String orderId, HttpServletRequest request) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(assignIds);
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(orderId));
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        Set<Position> positions = maintainOrder.getAssignPositions();
        if (positions == null) {
            positions = new HashSet<>();
        }
        List<Long> ids = new ArrayList<>();
        for (Object id : jsonArray) {
            Position position = positionBiz.findModel(StringConverters.null2Long(id));
            if (positions != null) {
                positions.add(position);
                ids = systemUserBiz.getUserIdsByPosition(id.toString(), null,enterprise.getId() + "");
            }
        }
        maintainOrder.setAssign(Boolean.TRUE);
        maintainOrder.setOrderAssignTypeEnum(OrderAssignTypeEnum.POSITION);
        maintainOrder.setAssignPositions(positions);
        dao.update(maintainOrder);
        //消息推送 TODO 推送给新的岗位人员
        String content = "维保单:" + maintainOrder.getOrderCode() + "等待接单!";
        planMessageSendBiz.senMsg(maintainOrder.getId(), "maintain", maintainOrder.getEnterprise(), ids, content);
        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.ASSIGN_POSITION, request);
        return ResultUtil.success();
    }


    /**
     * 指派岗位
     *
     * @param assignIds
     * @param orderId
     * @return
     */
    public ResultDto assignPositionsApp(String assignIds, String orderId, HttpServletRequest request) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(assignIds);
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(orderId));
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        Set<Position> positions = new HashSet<>();
        List<Long> ids = new ArrayList<>();
        for (Object id : jsonArray) {
            Position position = positionBiz.findModel(StringConverters.null2Long(id));
            if (positions != null) {
                positions.add(position);
                ids = systemUserBiz.getUserIdsByPosition(id.toString(),null, enterprise.getId() + "");
            }
        }
        maintainOrder.setAssign(Boolean.TRUE);
        maintainOrder.setOrderAssignTypeEnum(OrderAssignTypeEnum.POSITION);
        maintainOrder.setAssignPositions(positions);
        dao.update(maintainOrder);
        //消息推送 TODO 推送给新的岗位人员
        String content = "维保单:" + maintainOrder.getOrderCode() + "等待接单!";
        planMessageSendBiz.senMsg(maintainOrder.getId(), "maintain", maintainOrder.getEnterprise(), ids, content);
        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.ASSIGN_POSITION, request);
        return ResultUtil.success();
    }

    /**
     * 自定义hql查询接口
     *
     * @param hql
     * @param queryParam
     * @return
     */
    public List<MaintainOrder> hqlExcute(String hql, QueryParam queryParam) {
        return dao.hqlExcute(hql, queryParam);
    }


    /**
     * 查询列表接口
     *
     * @param status 状态 0 待接单，1进行中 2 审核中 3 完成 4批量审核 5批量转单
     * @return
     */
    public ResultDto list(String status, String pageIndex, String pageSize, SystemUser systemUser, Enterprise enterprise, String searchData, String date) {
        /**
         * 工单的批量审核权限
         */
        String auditAuthorityName = "ROLE_MAINTAIN_ORDER_BATCH_AUDIT";
        if (StringConverters.null2String(status).equals("4") && !systemAuthorityBiz.hasAuthAuthority(auditAuthorityName, systemUser.getId(), enterprise.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("records", 0);
            jsonObject.put("rows", new JSONArray());
            return ResultUtil.success(jsonObject);
        }
        /**
         * 判断当前用户是否是部门主管
         */
        boolean isLeader = false;
        String suoHql = "select obj from SystemUserOrganization obj where obj.systemUser.id=" + systemUser.getId() + " and obj.organization.enterprise.id = " + enterprise.getId();
        List<SystemUserOrganization> systemUserOrganizationList = systemUserOrganizationBiz.hqlExcute(suoHql);
        Organization organization = null;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationList) && systemUserOrganizationList.get(0).isLeader()) {
            organization = systemUserOrganizationList.get(0).getOrganization();//当前用户所在部门
            isLeader = true;
        }
        return dao.list(status, pageIndex, pageSize, systemUser, enterprise, searchData, date, isLeader, organization);
    }


    /**
     * 工单详情
     *
     * @param id
     * @return
     */
    public ResultDto detail(String id) {

        JSONArray buttons = new JSONArray();
        JSONArray unfinished = new JSONArray();
        JSONArray finished = new JSONArray();

        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(id));

        if (null == maintainOrder) {
            return ResultUtil.error("该工单不存在");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (null == systemUser) {
            return ResultUtil.error("用户未登录");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误");
        }


        QueryParam maintainParam = new QueryParam();
        maintainParam.getSqlMap().put("maintainOrderId", StringConverters.null2String(maintainOrder.getId()));
        List<FacilityMaintainSnap> FacilityMaintainSnaps = facilityMaintainSnapBiz.findList(maintainParam);
        JSONObject jsonObject = maintainOrder.toJSONObject();
        //工时计算
        net.sf.json.JSONObject workingTime= net.sf.json.JSONObject.fromObject(nowWorkHours(id).getData());
        if(maintainOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")){
            jsonObject.put("totalWorkingHours",workingTime.get("totalHours"));//总工时
            jsonObject.put("workingHours",workingTime.get("receiveHours"));//我的工时
        }
        jsonObject.put("beforeHours", maintainOrder.getWorkingHours());//退回重修前的工时
        jsonObject.put("beforeTotalHours",  maintainOrder.getTotalWorkingHours());//退回重修前的总工时
        for (FacilityMaintainSnap facilityMaintainSnap : FacilityMaintainSnaps) {
            JSONObject maintainObject = new JSONObject();
            maintainObject.put("facilityName", StringConverters.null2String(facilityMaintainSnap.getFacilityName()));
            maintainObject.put("facilityCode", StringConverters.null2String(facilityMaintainSnap.getFacilityCode()));
            maintainObject.put("facilityId", facilityMaintainSnap.getFacilityId());
            maintainObject.put("applicationId", facilityMaintainSnap.getApplicationScenariosId() == null ? "" : facilityMaintainSnap.getApplicationScenariosId());
            maintainObject.put("maintainName", StringConverters.null2String(facilityMaintainSnap.getMaintainName()));
            maintainObject.put("spec", StringConverters.null2String(facilityMaintainSnap.getSpec()));
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("facilityMaintainSnapId", StringConverters.null2String(facilityMaintainSnap.getId()));
            List<MaintainOrderWorkContent> maintainOrderWorkContents = maintainOrderWorkContentBiz.findList(queryParam);
            JSONArray contentArray = new JSONArray();
            JSONArray applicationArray = new JSONArray();
            for (MaintainOrderWorkContent maintain : maintainOrderWorkContents) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("applicationName", maintain.getApplication_scenarios_name());
                jsonObject1.put("applicationId", maintain.getApplication_scenarios_id());
                if (!applicationArray.contains(jsonObject1)) {
                    applicationArray.add(jsonObject1);
                }
            }
            maintainObject.put("snapId", facilityMaintainSnap.getId());
            maintainObject.put("applicationArray", applicationArray);
            for (MaintainOrderWorkContent maintain : maintainOrderWorkContents) {
                JSONObject contentObject = new JSONObject();
                contentObject.put("inputTypeEnum", StringConverters.null2String(maintain.getInputTypeEnum().getCode()));
                if ("COMPLETE_TYPE".equals(maintain.getInputTypeEnum().getCode()) || "STATUS_TYPE".equals(maintain.getInputTypeEnum().getCode())) {
                    String[] names = maintain.getInputTypeEnum().getName().split("、");
                    JSONArray nameArray = new JSONArray();
                    JSONObject nameS = new JSONObject();
                    nameS.put("content", "尚未选择");
                    nameS.put("isNormal", false);
                    nameArray.add(nameS);
                    for (String o : names) {
                        JSONObject nameStatus = new JSONObject();
                        if ("异常".equals(o) || "无此项目".equals(o) || "需处理（不能运转）".equals(o)) {
                            nameStatus.put("isNormal", false);
                        } else {
                            nameStatus.put("isNormal", true);
                        }
                        nameStatus.put("content", o);
                        nameArray.add(nameStatus);
                    }
//                    nameArray.addAll(Arrays.asList(names));
                    contentObject.put("inputType", nameArray);
                } else {
                    contentObject.put("inputType", StringConverters.null2String(maintain.getInputTypeEnum().getName()));
                }
                contentObject.put("contentId", StringConverters.null2Long(maintain.getId()));
                QueryParam contentParam = new QueryParam();
                contentParam.getSqlMap().put("contentId", StringConverters.null2String(maintain.getId()));
                List<WorkContentRemark> workContentRemarks = workContentRemarkBiz.findList(contentParam);
                if (CollectionUtils.isNotEmpty(workContentRemarks)) {
                    contentObject.put("hasRemark", 1);
                } else {
                    contentObject.put("hasRemark", 0);
                }
                contentObject.put("unit", StringConverters.null2String(maintain.getUnit()));
                contentObject.put("applicationId", StringConverters.null2Long(maintain.getApplication_scenarios_id()));
                contentObject.put("applicationName", StringConverters.null2String(maintain.getApplication_scenarios_name()));
                contentObject.put("photo", StringConverters.null2Boolean(maintain.getPhoto()));
                contentObject.put("maxNumber", StringConverters.null2Double(maintain.getMaxNumber()));
                contentObject.put("minNumber", StringConverters.null2Double(maintain.getMinNumber()));
                contentObject.put("abnormal", StringConverters.null2Boolean(maintain.getAbnormal()));
                contentObject.put("name", StringConverters.null2String(maintain.getName()));
                contentObject.put("content", StringConverters.null2String(maintain.getContent()));
                JSONArray array = new JSONArray();
                if (StringUtils.isNotBlank(maintain.getContent())) {
                    array = JSONArray.parseArray(maintain.getContent());
                }
                contentObject.put("contentArray", array);
                contentObject.put("category", StringConverters.null2String(maintain.getCategory()));
                contentObject.put("result", StringConverters.null2String(maintain.getResult()));
                JSONArray photoArray = new JSONArray();
                if (maintain.getContentPhoto() != null) {
                    List<Resource> contentPhotos = new ArrayList<>(maintain.getContentPhoto());
                    contentPhotos.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
                    if (CollectionUtils.isNotEmpty(contentPhotos)) {
                        for (Resource resource : contentPhotos) {
                            photoArray.add(resource.getPath());
                        }
                    }
                }
                contentObject.put("photos", photoArray);
                String path = "";
                if (StringUtils.isNotBlank(maintain.getResourceIds())) {
                    Resource model = resourceBiz.findModel(StringConverters.null2Long(maintain.getResourceIds()));
                    if (model != null) {
                        path = model.getPath();
                    }

                }
                contentObject.put("resources", path);
                contentArray.add(contentObject);
            }
            maintainObject.put("contents", contentArray);
            if (facilityMaintainSnap.isCompleted()) {
                finished.add(maintainObject);
            } else {
                unfinished.add(maintainObject);
            }
        }

        jsonObject.put("finished", finished);
        jsonObject.put("unfinished", unfinished);

        systemUser = systemUserBiz.findModel(StringConverters.null2Long(systemUser.getId()));
        Set<SystemUserOrganization> systemUserOrganizationSet = systemUser.getSystemUserOrganizationSet();
        boolean leader = false;
        Organization organization = null;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationSet)) {
            //所属部门
            leader = systemUserOrganizationSet.iterator().next().isLeader();
            organization = systemUserOrganizationSet.iterator().next().getOrganization();
        }


        String takingAuthorityName = "ROLE_ENTERPRISE_MAINTAIN_ORDER_TAKING";
        String auditAuthorityName = "ROLE_ENTERPRISE_MAINTAIN_ORDER_AUDIT";
        String assignAuthorityName = "ROLE_ENTERPRISE_MAINTAINING_PLANNER_ORDER_ASSIGN";
        // 批量转单权限code
        String transfersHorityName = "ROLE_ENTERPRISE_MAINTAIN_BATCH_TRANSFER";

        String code = maintainOrder.getOrderStatusEnum().getCode();

        boolean hasAuth = false;
        if (("WAIT_PRESENCE".equals(code) || "UNFINISHED".equals(code)) && (maintainOrder.getCancel() ||
                maintainOrder.getDelay())) {//判断工单取消和延期按钮
            if (systemAuthorityBiz.hasAuthAuthority(auditAuthorityName, systemUser.getId(), enterprise.getId())) {
                if (organization != null) {
                    if (maintainOrder.getAuditSystemUser() != null || maintainOrder.getPosition() != null) {
                        if ((maintainOrder.getOrganization() == organization && maintainOrder.getAuditSystemUser() == systemUser)) {
                            hasAuth = true;
                            buttons.add("passButton");
                            buttons.add("rejectButton");
                        } else if (maintainOrder.getOrganization() == organization && maintainOrder.getPosition() == systemUser.getPosition(enterprise, systemUser.getPositionSet())) {
                            hasAuth = true;
                            buttons.add("passButton");
                            buttons.add("rejectButton");
                        }
                    }
                }
            }
        }

        if ("WAIT_TAKING".equals(code)) {
            if (systemAuthorityBiz.hasAuthAuthority(assignAuthorityName, systemUser.getId(), enterprise.getId())) {
                buttons.add("assignButton");
            }
            if (systemAuthorityBiz.hasAuthAuthority(takingAuthorityName, systemUser.getId(), enterprise.getId())) {
                //指定接单人的，需要判断我发起的工单有没有指派
                Position position=systemUser.getPosition(enterprise,systemUser.getPositionSet());//获取当前企业下的职位
                if(maintainOrder.getAssign()&&(maintainOrder.getAssignUsers().contains(systemUser)||maintainOrder.getAssignPositions().contains(position))){
                    buttons.add("takingButton");
                } else if (!maintainOrder.getAssign()) {
                    // 如果不是指派的，但有接单权限，给按钮
                    buttons.add("takingButton");
                }
            }
        } else if ("WAIT_PRESENCE".equals(code)) {
            if (!hasAuth && maintainOrder.getReceiveUser() == systemUser) {
                buttons.add("presenceButton");
                if (!maintainOrder.getDelay() && !maintainOrder.getCancel()) {
                    buttons.add("cancelButton");
                    buttons.add("delayButton");
                }
                // 如果这个人有批量转单的权限，就给他添加转单的权限判断等操作，如果他没有批量转单的权限，就不给他有转单权限
                // 转单权限
                if (systemAuthorityBiz.hasAuthAuthority(transfersHorityName, systemUser.getId(), enterprise.getId())) {
                    if (!maintainOrder.getCancel()) {
                        buttons.add("transferButton");
                    }
                }

            }
        } else if ("UNFINISHED".equals(code)) {
            if (!hasAuth && maintainOrder.getReceiveUser() == systemUser) {
                if (!maintainOrder.getDelay() && !maintainOrder.getCancel()) {
                    buttons.add("cancelButton");
                    buttons.add("delayButton");
                }
                if (systemAuthorityBiz.hasAuthAuthority(transfersHorityName, systemUser.getId(), enterprise.getId())) {
                    if (!maintainOrder.getCancel()) {
                        buttons.add("transferButton");
                    }
                }
                buttons.add("saveButton");
                buttons.add("submitButton");
            }
        } else if ("REJECTED".equals(code)) {
            if (maintainOrder.getReceiveUser() == systemUser) {
                buttons.add("presenceButton");
            }
        } else if ("IN_AUDITING".equals(code)) {
            if (systemAuthorityBiz.hasAuthAuthority(auditAuthorityName, systemUser.getId(), enterprise.getId())) {
                if (organization != null) {
                    if (maintainOrder.getAuditSystemUser() != null || maintainOrder.getPosition() != null) {
                        if ((maintainOrder.getOrganization() == organization && maintainOrder.getAuditSystemUser() == systemUser)) {
                            buttons.add("passButton");
                            buttons.add("rejectButton");
                        } else if (maintainOrder.getOrganization() == organization && maintainOrder.getPosition() == systemUser.getPosition(enterprise, systemUser.getPositionSet())) {
                            buttons.add("passButton");
                            buttons.add("rejectButton");
                        }
                    }
                }
            }

        }

        QueryParam queryParam1 = new QueryParam();
        queryParam1.getSqlMap().put("maintainOrderId", StringConverters.null2String(maintainOrder.getId()));
        queryParam1.getSqlMap().put("applyType", "CANCEL");
        queryParam1.setSqlOrder(" order by createDate ");
        List<ApplyOrder> applyOrders = applyOrderBiz.findList(queryParam1);
        if (CollectionUtils.isNotEmpty(applyOrders)) {
            jsonObject.put("cancelReason", applyOrders.get(applyOrders.size() - 1).getReason());
            jsonObject.put("cancelType", applyOrders.get(applyOrders.size() - 1).getDictInfo() == null ? "" : applyOrders.get(applyOrders.size() - 1).getDictInfo().getPropertyName());

        }

        queryParam1.getSqlMap().put("applyType", "DELAY");
        applyOrders = applyOrderBiz.findList(queryParam1);
        if (CollectionUtils.isNotEmpty(applyOrders)) {
            jsonObject.put("delayReason", applyOrders.get(applyOrders.size() - 1).getReason());
            jsonObject.put("delayType", applyOrders.get(applyOrders.size() - 1).getDictInfo() == null ? "" : applyOrders.get(applyOrders.size() - 1).getDictInfo().getPropertyName());
        }

        JSONArray completeArray = new JSONArray();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("maintainOrderId", StringConverters.null2String(maintainOrder.getId()));
        queryParam.getSqlMap().put("auditType", "COMPLETE");
        queryParam.setSqlOrder("order by createDate ");
        List<AuditOrder> auditOrders = auditOrderBiz.findList(queryParam);
        for (AuditOrder auditOrder : auditOrders) {
            completeArray.add(auditOrder.toJSONObject());
        }

        JSONArray delayArray = new JSONArray();
        queryParam.getSqlMap().put("auditType", "DELAY");
        auditOrders = auditOrderBiz.findList(queryParam);
        for (AuditOrder auditOrder : auditOrders) {
            delayArray.add(auditOrder.toJSONObject());
        }

        JSONArray cancelArray = new JSONArray();
        queryParam.getSqlMap().put("auditType", "CANCEL");
        auditOrders = auditOrderBiz.findList(queryParam);
        for (AuditOrder auditOrder : auditOrders) {
            cancelArray.add(auditOrder.toJSONObject());
        }

        QueryParam partnerParam = new QueryParam();
        partnerParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        partnerParam.getSqlMap().put("maintainOrderId", StringConverters.null2String(maintainOrder.getId()));
        List<MaintainPartner> partners = maintainPartnerBiz.findList(partnerParam);
        JSONArray partnerArray = new JSONArray();
        for (MaintainPartner maintainPartner : partners) {
            JSONObject partnerObject = new JSONObject();
            partnerObject.put("deleteStatus", maintainPartner.isDeleteStatus());
            partnerObject.put("partnerId", maintainPartner.getId());
            partnerObject.put("userId", maintainPartner.getPartner().getId());
            partnerObject.put("userName", maintainPartner.getPartner().getUserName());
            partnerObject.put("workingHours", maintainPartner.getWorkingHours());
            partnerArray.add(partnerObject);
        }
        jsonObject.put("partner", partnerArray);
        jsonObject.put("completeArray", completeArray);
        jsonObject.put("delayArray", delayArray);
        jsonObject.put("cancelArray", cancelArray);
        jsonObject.put("buttons", buttons);
        jsonObject.put("isFocus", isFocus(id, systemUser, enterprise));
        jsonObject.put("systemUserId", systemUser.getId());
        return ResultUtil.success(jsonObject);
    }

    /**
     * 接单方法
     *
     * @param id 工单关键字ID
     * @return
     */
    public ResultDto receive(String id) {
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(id));
        if (null == maintainOrder) {
            return ResultUtil.error("该工单不存在");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (null == systemUser) {
            return ResultUtil.error("用户未登录");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误");
        }

        if (!maintainOrder.getOrderStatusEnum().getCode().equals("WAIT_TAKING")) {
            return ResultUtil.error("该工单已不在待接单列表中，请刷新查看");
        }

        maintainOrder.setReceiveUser(systemUser);
        maintainOrder.setOrderStatusEnum(OrderStatusEnum.WAIT_PRESENCE);
        maintainOrder.setReceiveDate(new Date());
        maintainOrder.setReceive(true);
        dao.update(maintainOrder);
        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.RECEIVE_ORDER, request);

        //工时管理
        WorkingHours workingHours;
        QueryParam queryParam2 = new QueryParam();
        queryParam2.getSqlMap().put("partnerId", StringConverters.null2String(systemUser.getId()));
        queryParam2.getSqlMap().put("maintainOrderId", StringConverters.null2String(maintainOrder.getId()));
        List<WorkingHours> workingHoursList = workingHoursBiz.findList(queryParam2);
        if (CollectionUtil.isNotEmpty(workingHoursList)) {
            workingHours = workingHoursList.get(0);
        } else {
            workingHours = new WorkingHours();
            workingHours.setActualWorkingHours(0);
        }
        workingHours.setMaintainOrder(maintainOrder);
        workingHours.setWorkingHoursStatusEnum(WorkingHoursStatusEnum.RUN);
        workingHours.setPartner(systemUser);
        workingHours.setCharge(true);
        workingHours.setEnterprise(enterprise);
        workingHoursBiz.addOrUpdate(workingHours);
        //推送消息
        SystemUser reportUser = maintainOrder.getCreateUser();
        String content = "维保单:" + maintainOrder.getOrderCode() + ",已被" + systemUser.getUserName() + "接单。";
        List<Long> ids = new ArrayList<>();
        ids.add(reportUser.getId());
        planMessageSendBiz.senMsg(maintainOrder.getId(), "maintain", enterprise, ids, content);
        return ResultUtil.success();
    }

    /**
     * 到场方法
     *
     * @param id 工单关键字ID
     * @return
     */
    public ResultDto present(String id, String longitude, String latitude) {
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(id));
        if (null == maintainOrder) {
            return ResultUtil.error("该工单不存在");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (null == systemUser) {
            return ResultUtil.error("用户未登录");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误");
        }
        maintainOrder.setPresenceUser(systemUser);
        maintainOrder.setOrderStatusEnum(OrderStatusEnum.UNFINISHED);
        maintainOrder.setPresenceTime(new Date());
        maintainOrder.setPresence(true);
        maintainOrder.setLongitude(StringConverters.null2BigDecimal(longitude));
        maintainOrder.setLatitude(StringConverters.null2BigDecimal(latitude));
        maintainOrder.setMark(false);
        dao.update(maintainOrder);
        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.RRESENT_ORDER, request);
        return ResultUtil.success();
    }


    /**
     * 审核工单接口
     *
     * @param orderId 工单ID
     * @param result  结果 0通过 -1 不通过
     * @param remark  留言
     * @return
     */
    public ResultDto audit(String orderId, String result, String remark) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (null == systemUser) {
            return ResultUtil.error("用户未登录");
        }
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(orderId));
        if (null == maintainOrder) {
            return ResultUtil.error("该工单不存在");
        }


        return ResultUtil.success();
    }

    public ResultDto partnerList(String id) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(id));
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("maintainOrderId", id);
        List<MaintainPartner> maintainPartners = maintainPartnerBiz.findList(queryParam);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (maintainOrder.getReceiveUser() != null) {
            jsonObject.put("reason", "");
            jsonObject.put("name", StringConverters.null2String(maintainOrder.getReceiveUser().getUserName()));
            jsonObject.put("phone", StringConverters.null2String(maintainOrder.getReceiveUser().getMobile()));
            jsonObject.put("userId", StringConverters.null2String(maintainOrder.getReceiveUser().getId()));
            jsonObject.put("tag", "main");
            jsonArray.add(jsonObject);
        }

        for (MaintainPartner maintainPartner : maintainPartners) {
            jsonObject = new JSONObject();
            jsonObject.put("reason", StringConverters.null2String(maintainPartner.getReason()));
            jsonObject.put("userId", StringConverters.null2String(maintainPartner.getPartner().getId()));
            jsonObject.put("name", StringConverters.null2String(maintainPartner.getPartner().getUserName()));
            jsonObject.put("phone", StringConverters.null2String(maintainPartner.getPartner().getMobile()));
            jsonObject.put("tag", "partner");
            jsonArray.add(jsonObject);
        }

        result.put("list", jsonArray);
        return ResultUtil.success(result);
    }


    public ResultDto removePartner(String id) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        maintainPartnerBiz.deleteLogic(maintainPartnerBiz.findModel(StringConverters.null2Long(id)));
        return ResultUtil.success();
    }


    public ResultDto addPartner(String id, String partnerArray) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        if (StringUtils.isNotBlank(partnerArray)) {
            JSONArray array = JSONArray.parseArray(partnerArray);
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < array.size(); i++) {

                JSONObject j = array.getJSONObject(i);

                String userId = AliJsonObjectCover.ObjectString(j, "userId");

                QueryParam queryParam = new QueryParam();
                queryParam.getSqlMap().put("partnerId", userId);
                queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
                queryParam.getSqlMap().put("maintainOrderId", id);
                List<MaintainPartner> list = maintainPartnerBiz.findList(queryParam);
                MaintainPartner maintainPartner;
                if (CollectionUtils.isNotEmpty(list)) {
                    maintainPartner = list.get(0);
                } else {
                    maintainPartner = new MaintainPartner();
                }

                MaintainOrder maintainOrder = findModel(StringConverters.null2Long(id));
                maintainPartner.setMaintainOrder(maintainOrder);
                maintainPartner.setEnterprise(sessionEnterprise);
                String reason = AliJsonObjectCover.ObjectString(j, "reason");
                if (StringUtils.isNotBlank(reason)) {
                    maintainPartner.setReason(reason);
                }

                String teamworkCatId = AliJsonObjectCover.ObjectString(j, "teamworkCatId");
                if (StringUtils.isNotBlank(teamworkCatId)) {
                    DictInfo model = dictInfoBiz.findModel(StringConverters.null2Long(teamworkCatId));
                    maintainPartner.setTeamworkCat(model);
                }

                if (StringUtils.isNotBlank(userId)) {
                    maintainPartner.setPartner(systemUserBiz.findModel(StringConverters.null2Long(userId)));
                }
                String content = AliJsonObjectCover.ObjectString(j, "content");
                if (StringUtils.isNotBlank(content)) {
                    maintainPartner.setContent(content);
                }
                maintainPartnerBiz.addOrUpdate(maintainPartner);
                jsonArray.add(maintainPartner.getId());


                //工时管理
                WorkingHours workingHours;
                QueryParam queryParam2 = new QueryParam();
                queryParam2.getSqlMap().put("partnerId", StringConverters.null2String(systemUser.getId()));
                queryParam2.getSqlMap().put("maintainOrderId", StringConverters.null2String(maintainOrder.getId()));
                List<WorkingHours> workingHoursList = workingHoursBiz.findList(queryParam2);
                if (CollectionUtil.isNotEmpty(workingHoursList)) {
                    workingHours = workingHoursList.get(0);
                } else {
                    workingHours = new WorkingHours();
                    workingHours.setActualWorkingHours(0);
                }
                workingHours.setMaintainOrder(maintainOrder);
                workingHours.setWorkingHoursStatusEnum(WorkingHoursStatusEnum.RUN);
                workingHours.setPartner(systemUser);
                workingHours.setCharge(false);
                workingHours.setEnterprise(sessionEnterprise);
                workingHoursBiz.addOrUpdate(workingHours);
            }
            result.put("partnerIds", jsonArray);
        }
        return ResultUtil.success(result);
    }

    /**
     * 参与人详情
     *
     * @param id
     * @param userId
     * @param tag
     * @return
     */
    public ResultDto partnerDetail(String id, String userId, String tag) {
        JSONObject jsonObject = new JSONObject();
        SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(userId));
        jsonObject.put("name", systemUser.getUserName());
        jsonObject.put("phone", systemUser.getMobile());
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(id));
        JSONArray contentArray = new JSONArray();
        if ("partner".equals(tag)) {
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(maintainOrder.getEnterprise().getId()));
            queryParam.getSqlMap().put("maintainOrderId", id);
            queryParam.getSqlMap().put("partnerId", userId);
            List<MaintainPartner> maintainPartners = maintainPartnerBiz.findList(queryParam);
            if (CollectionUtils.isNotEmpty(maintainPartners) && maintainPartners.size() == 1) {
                MaintainPartner maintainPartner = maintainPartners.get(0);
                jsonObject.put("reason", maintainPartner.getReason());
                jsonObject.put("teamworkCat", maintainPartner.getTeamworkCat() == null ? "" : maintainPartner.getTeamworkCat().getPropertyName());
                Set<String> snapSet = new HashSet<>();
                JSONArray jsonArray = JSONArray.parseArray(maintainPartner.getContent());
                for (int i = 0; i < jsonArray.size(); i++) {
                    snapSet.add(jsonArray.getJSONObject(i).getString("snap"));
                }
                snapSet.forEach(x -> {
                    JSONObject contentObject = new JSONObject();
                    contentObject.put("facilityName", facilityMaintainSnapBiz.findModel(StringConverters.null2Long(x)).getFacilityName());
                    JSONArray contentDetail = new JSONArray();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        if (x.equals(jsonArray.getJSONObject(i).getString("snap"))) {
                            contentDetail.add(maintainOrderWorkContentBiz.findModel(StringConverters.null2Long(jsonArray.getJSONObject(i).get("content"))).getName());
                        }
                    }
                    contentObject.put("contentDetail", contentDetail);
                    contentArray.add(contentObject);
                });
            }
        } else if ("main".equals(tag)) {
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("maintainOrderId", id);
            List<FacilityMaintainSnap> facilityMaintainSnaps = facilityMaintainSnapBiz.findList(queryParam);
            facilityMaintainSnaps.forEach(x -> {
                JSONObject contentObject = new JSONObject();
                contentObject.put("facilityName", x.getFacilityName());
                QueryParam contentParam = new QueryParam();
                contentParam.getSqlMap().put("distribute", "true");
                contentParam.getSqlMap().put("facilityMaintainSnapId", x.getId() + "");
                List<MaintainOrderWorkContent> maintainOrderWorkContents = maintainOrderWorkContentBiz.findList(queryParam);
                JSONArray contentDetail = new JSONArray();
                maintainOrderWorkContents.forEach(y -> {
                    contentDetail.add(y.getName());
                });
                contentObject.put("contentDetail", contentDetail);
                contentArray.add(contentObject);
            });
        }
        jsonObject.put("row", contentArray);
        return ResultUtil.success(jsonObject);
    }


    /**
     * 审核工单接口
     *
     * @param orderId 工单ID
     * @param result  结果 0通过 -1 不通过
     * @param remark  留言
     * @return
     */
    public ResultDto audit(String orderId, String result, String remark, SystemUser systemUser, HttpServletRequest request) {
   /* SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
    if (null == systemUser) {
        return ResultUtil.error("用户未登录");
    }*/
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(orderId));
        if (null == maintainOrder) {
            return ResultUtil.error("该工单不存在");
        }
        int level = maintainOrder.getLevel();
        if (!maintainOrder.getCancel() && !maintainOrder.getDelay() && !maintainOrder.isAuditing()) {
            return ResultUtil.error("该工单不在审核状态中");
        }
        String content = "";
        ApplyOrder applyOrder = maintainOrder.getApplyOrder();
        if (null != applyOrder && !maintainOrder.isAuditing()) {//完成审核不改变申请
            applyOrder.setLevel(level);
            if (StringConverters.null2String(result).equals("-1")) {
                applyOrder.setEffective(false);
            }
            applyOrderBiz.update(applyOrder);
        }

        maintainOrder.setAuditFirst(false);//去除初审标签
        maintainOrder.setPosition(null);
        maintainOrder.setAuditSystemUser(null);
        maintainOrder.setOrganization(null);

        if (maintainOrder.getDelay()) {
            //延期审批
            if (null == maintainOrder.getDelayFlowID()) {//未配置审批流
                maintainOrder.setLevel(0);
                maintainOrder.setDelay(false);
                maintainOrder.setDelayRealTime(maintainOrder.getDelayTime() == null ? maintainOrder.getDelayRealTime() : maintainOrder.getDelayTime());
            } else {
                JSONArray jsonArray = JSONArray.parseArray(maintainOrder.getDelayFlow());
                if (0 == jsonArray.size()) {//配置的审批流  没有配置节点
                    maintainOrder.setLevel(0);
                    maintainOrder.setDelay(false);
                    maintainOrder.setDelayRealTime(maintainOrder.getDelayTime() == null ? maintainOrder.getDelayRealTime() : maintainOrder.getDelayTime());
                }
                if (level == jsonArray.size()&&StringConverters.null2String(result).equals("0")) {//终极审批  审核完结
                    content = "维保单:" + maintainOrder.getOrderCode() + ",已完成审核";
                    maintainOrder.setLevel(0);
                    maintainOrder.setDelay(false);//审核完结  置为初始
                    maintainOrder.setPosition(null);
                    maintainOrder.setAuditSystemUser(null);
                    maintainOrder.setOrganization(null);
                    maintainOrder.setAuditLast(false); //去除终审标签
                    maintainOrder.setEndDateTime(maintainOrder.getDelayTime());
                    if (StringConverters.null2String(result).equals("0")) {//审核通过
                        maintainOrder.setDelayRealTime(maintainOrder.getDelayTime() == null ? maintainOrder.getDelayRealTime() : maintainOrder.getDelayTime());
                    }
                } else {
                    if (StringConverters.null2String(result).equals("0")) {//审核通过
                        content = "维保单:" + maintainOrder.getOrderCode() + "," + systemUser.getUserName() + "延期审核通过";
                        if (level == 0) {
                            level = 1;
                        }
                        if (jsonArray.size() - level == 1) { //用于判断是不是最后一级审核
                            maintainOrder.setAuditLast(true);
                        }
                        JSONObject jsonObject = (JSONObject) jsonArray.get(level);
                        maintainOrder.setLevel(level + 1);
                        maintainOrder.setOrganization(organizationBiz.findModel(StringConverters.null2Long(jsonObject.getString("organizationId"))));
                        String auditType = jsonObject.getString("nodeTypeEnum");
                        if (StringConverters.null2String(auditType).equals("USER")) {//审批类型  用户或者岗位
                            maintainOrder.setAuditSystemUser(systemUserBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                        } else {
                            maintainOrder.setPosition(positionBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                        }
                    } else {//审核不通过
                        content = "维保单:" + maintainOrder.getOrderCode() + "," + systemUser.getUserName() + "延期审核驳回";
                        maintainOrder.setLevel(0);
                        maintainOrder.setDelay(false);//审核完结  置为初始
                        maintainOrder.setPosition(null);
                        maintainOrder.setAuditSystemUser(null);
                        maintainOrder.setOrganization(null);
                        maintainOrder.setAuditLast(false);
                    }
                }
            }
            dao.update(maintainOrder);
            /*****添加审核日志*****/
            auditOrderBiz.saveOrUpdate(maintainOrder, systemUser, StringConverters.null2String(result).equals("0"), remark, AuditTypeEnum.DELAY, level);
        } else if (maintainOrder.getCancel()) {
            //取消审批
            if (null == maintainOrder.getCancelFlowID()) {//未配置审批流
                maintainOrder.setLevel(0);
                maintainOrder.setCancel(false);
                maintainOrder.setOrderStatusEnum(OrderStatusEnum.CANCEL);
            } else {
                // 取消审批，获取取消审批流信息
                JSONArray jsonArray = JSONArray.parseArray(maintainOrder.getCancelFlow());
                if (jsonArray == null || 0 == jsonArray.size()) {//配置的审批流  没有配置节点
                    maintainOrder.setLevel(0);
                    maintainOrder.setCancel(false);
                    maintainOrder.setOrderStatusEnum(OrderStatusEnum.CANCEL);
                }
                if (jsonArray != null && level == jsonArray.size()&&StringConverters.null2String(result).equals("0")) {//终极审批  审核完结
                    content = "维保单:" + maintainOrder.getOrderCode() + ",已完成审核";
                    maintainOrder.setLevel(0);
                    maintainOrder.setCancel(false);//审核完结  置为初始
                    maintainOrder.setPosition(null);
                    maintainOrder.setAuditSystemUser(null);
                    maintainOrder.setOrganization(null);
                    maintainOrder.setAuditLast(false);
                    if (StringConverters.null2String(result).equals("0")) {//审核通过
                        maintainOrder.setOrderStatusEnum(OrderStatusEnum.CANCEL);
                    }
                } else {
                    content = "维保单:" + maintainOrder.getOrderCode() + "," + systemUser.getUserName() + "取消审核通过";
                    if (StringConverters.null2String(result).equals("0")) {
                        //审核通过
                        if (level == 0) {
                            level = 1;
                        }

                        //
                        if (jsonArray.size() == 1) {
                            maintainOrder.setAuditLast(true);
                        } else if (jsonArray.size() - level == 1 && jsonArray.size() != 2) {
                            //用于判断是不是最后一级审核  添加终审标签
                            maintainOrder.setAuditLast(true);
                        }
                        JSONObject jsonObject = (JSONObject) jsonArray.get(level);
                        maintainOrder.setLevel(level + 1);
                        maintainOrder.setOrganization(organizationBiz.findModel(StringConverters.null2Long(jsonObject.getString("organizationId"))));
                        String auditType = jsonObject.getString("nodeTypeEnum");
                        if (StringConverters.null2String(auditType).equals("USER")) {
                            //审批类型  用户或者岗位
                            maintainOrder.setAuditSystemUser(systemUserBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                        } else {
                            maintainOrder.setPosition(positionBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                        }
                    } else {
                        //审核不通过
                        content = "维保单:" + maintainOrder.getOrderCode() + "," + systemUser.getUserName() + "取消审核驳回";
                        maintainOrder.setLevel(0);
                        maintainOrder.setCancel(false);//审核完结  置为初始
                        maintainOrder.setPosition(null);
                        maintainOrder.setAuditSystemUser(null);
//                       maintainOrder.setOrderStatusEnum(OrderStatusEnum.WAIT_PRESENCE);
                        maintainOrder.setOrganization(null);
                        maintainOrder.setAuditLast(false);

                    }
                }
            }
            dao.update(maintainOrder);

            /*****添加审核日志*****/
            auditOrderBiz.saveOrUpdate(maintainOrder, systemUser, StringConverters.null2String(result).equals("0"), remark, AuditTypeEnum.CANCEL, level);
        } else if (maintainOrder.isAuditing()) {
            //完成审批
            if (null == maintainOrder.getAuditCompleteID()) {//未配置审批流
                maintainOrder.setLevel(0);
                maintainOrder.setAuditing(false);
                maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);
            } else {
                JSONArray jsonArray = JSONArray.parseArray(maintainOrder.getCompleteFlow());
                if (0 == jsonArray.size()) {//配置的审批流  没有配置节点
                    maintainOrder.setLevel(0);
                    maintainOrder.setAuditing(false);
                    maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);
                }
                if (level == jsonArray.size()&&StringConverters.null2String(result).equals("0")) {
                    //终极审批  审核完结
                    content = "维保单:" + maintainOrder.getOrderCode() + ",已完成审核";
                    maintainOrder.setLevel(0);
                    maintainOrder.setAuditing(false);//审核完结  置为初始
                    maintainOrder.setPosition(null);
                    maintainOrder.setAuditSystemUser(null);
                    maintainOrder.setOrganization(null);
                    maintainOrder.setAuditLast(false);
                    if (StringConverters.null2String(result).equals("0")) {//审核通过
                        maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);
                    } else {
                        maintainOrder.setOrderStatusEnum(OrderStatusEnum.WAIT_PRESENCE);
                    }
                } else {
                    content = "维保单:" + maintainOrder.getOrderCode() + "," + systemUser.getUserName() + "审核通过";
                    if (StringConverters.null2String(result).equals("0")) {//审核通过
                        if (level == 0) {
                            level = 1;
                        }
                        if (jsonArray.size() - level == 1) { //用于判断是不是最后一级审核  添加终审标签
                            maintainOrder.setAuditLast(true);
                        }
                        JSONObject jsonObject = (JSONObject) jsonArray.get(level);
                        maintainOrder.setLevel(level + 1);
                        maintainOrder.setOrganization(organizationBiz.findModel(StringConverters.null2Long(jsonObject.getString("organizationId"))));
                        String auditType = jsonObject.getString("nodeTypeEnum");
                        if (StringConverters.null2String(auditType).equals("USER")) {//审批类型  用户或者岗位
                            maintainOrder.setAuditSystemUser(systemUserBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                        } else {
                            maintainOrder.setPosition(positionBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                        }
                    } else {//审核不通过
                        content = "维保单:" + maintainOrder.getOrderCode() + "," +systemUser.getUserName() + "审核驳回";
                        maintainOrder.setLevel(0);
                        maintainOrder.setAuditing(false);//审核完结  置为初始
                        maintainOrder.setPosition(null);
                        maintainOrder.setAuditSystemUser(null);
                        maintainOrder.setOrganization(null);
                        maintainOrder.setOrderStatusEnum(OrderStatusEnum.WAIT_PRESENCE);
                        maintainOrder.setAuditLast(false);

                    }
                }
            }
            dao.update(maintainOrder);


            /*****添加审核日志*****/
            auditOrderBiz.saveOrUpdate(maintainOrder, systemUser, StringConverters.null2String(result).equals("0"), remark, AuditTypeEnum.COMPLETE, level);
        }
        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, result.equals("0") ? OrderOperationEnum.AUDIT : OrderOperationEnum.REJECT, request);


        //消息推送
        SystemUser receiveUser = maintainOrder.getReceiveUser();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("userId", StringConverters.null2String(receiveUser.getId()));
        List<UserDevice> userDevices = userDeviceBiz.findList(queryParam);
        List<MessageVO> messageVOS = new ArrayList<>();
        List<SystemUser> users = new ArrayList<>();
        users.add(receiveUser);
        for (UserDevice userDevice : userDevices) {
            messageVOS.add(new MessageVO(userDevice.getDeviceType(), userDevice.getDeviceToken()));
        }
        if (CollectionUtils.isNotEmpty(messageVOS)) {
            ThreadUtils.sendDeviceMessages(messageVOS, content, MessageTypeEnum.MAINTAIN, messageBiz, StringConverters.null2String(sessionEnterprise.getId()), maintainOrder.getOrderCode());
        }
        return ResultUtil.success();
    }

    /**
     * PC端批量审批工单
     *
     * @param ids
     * @param type
     * @param reason
     * @param request
     * @return
     */
    public ResultDto auditOrder(String ids, String type, String reason, String score, String remark, HttpServletRequest request) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(ids);
        if (type.equals("1")) {//终审
            batchAudit(ids, score, remark, systemUser, request);
        } else {
            jsonArray.forEach(x -> {
                audit(x.toString(), type.equals("0") ? "0" : "-1", reason, systemUser, request);
            });
        }

        return ResultUtil.success();
    }

    /**
     * 工作流程
     *
     * @param id
     * @return
     */
    public ResultDto workProgress(String id) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("maintainOrderId", id);
        String progress = "('RECEIVE_ORDER','RRESENT_ORDER','TRANSFER','SUBMIT_ORDER','TEMP_SUBMIT_ORDER','CANCEL_ORDER','DELAY_ORDER')";//工作流程，接单，到场，转单，临时保存，完成维保，取消申请，延期申请
        queryParam.getSqlMap().put("progress", progress);
        queryParam.setSqlOrder("order by id");
        List<MaintainOrderLog> maintainOrderLogList = maintainOrderLogBiz.findList(queryParam);
        JSONArray jsonArray = new JSONArray();
        //开始时间
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(id));
        //审批记录
        Set<AuditOrder> auditOrders = maintainOrder.getAuditOrders();
        auditOrders.forEach(x -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("createDate", CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(x.getCreateDate()), ""));
            jsonObject.put("userName", x.getAuditUser().getUserName());
            jsonObject.put("operation", x.getPass() ? (NumberUtil.convert(x.getLevel()) + "级审核") : "驳回");
            jsonArray.add(jsonObject);
        });
        //其他日志流程
        JSONObject startObject = new JSONObject();
        startObject.put("createDate", DateTimeUtils.formatDateToStringWithTime(maintainOrder.getStartDateTime()));
        startObject.put("userName", maintainOrder.getCreateUser().getUserName());
        startObject.put("operation", "开始");
        jsonArray.add(startObject);
        for (MaintainOrderLog maintainOrderLog : maintainOrderLogList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("createDate", CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(maintainOrderLog.getCreateDate()), ""));
            jsonObject.put("operation", maintainOrderLog.getOrderOperationEnum().getName());
            jsonObject.put("userName", maintainOrderLog.getUserName());
            jsonArray.add(jsonObject);
        }
        //对jsonArray进行排序
        jsonArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getDate("createDate")));
        JSONObject result = new JSONObject();
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }

    /**
     * 关注/取消关注
     */
    public ResultDto focus(String maintainOrderId, Boolean type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || enterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        // 关注
        if (type) {
            MaintainFocus maintainFocus = new MaintainFocus();
            maintainFocus.setEnterprise(enterprise);
            maintainFocus.setSystemUser(systemUser);
            maintainFocus.setMaintainOrder(dao.findModel(StringConverters.null2Long(maintainOrderId)));
            maintainFocusBiz.addOrUpdate(maintainFocus);
        } else {
            // 取消关注
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
            queryParam.getSqlMap().put("maintainOrderId", maintainOrderId);
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
            List<MaintainFocus> maintainFocusList = maintainFocusBiz.findList(queryParam);
            for (MaintainFocus maintainFocus : maintainFocusList) {
                maintainFocusBiz.delete(maintainFocus.getId());
            }
        }
        return ResultUtil.success();
    }

    /**
     * 工单是否关注了
     *
     * @param maintainOrderId
     * @param systemUser
     * @param enterprise
     * @return
     */
    public Boolean isFocus(String maintainOrderId, SystemUser systemUser, Enterprise enterprise) {
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("maintainOrderId", maintainOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
        List<MaintainFocus> maintainFocusList = maintainFocusBiz.findList(queryParam);
        if (CollectionUtils.isEmpty(maintainFocusList)) {
            return false;
        }
        return true;
    }

    /**
     * 计算工单完成百分比(以及工单是否异常 以及更新maintainOrder表工时字段)
     */
    public void updatePercent(String maintainOrderId) {
        MaintainOrder maintainOrder = this.findModel(StringConverters.ToLong(maintainOrderId));
        if (maintainOrder == null) {
            return;
        }
        maintainOrder.setMark(true);
        //百分比
        int totalCount = 0;
        int finishCount = 0;
        boolean flagSnap=false;
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("maintainOrderId", maintainOrderId);//查询所有的设备工艺
        List<FacilityMaintainSnap> facilityMaintainSnapList = facilityMaintainSnapBiz.findList(queryParam);
        if (CollectionUtils.isNotEmpty(facilityMaintainSnapList)) {
            for (FacilityMaintainSnap facilityMaintainSnap : facilityMaintainSnapList) {
                JSONArray applicationArray = new JSONArray();
                QueryParam queryParam1 = new QueryParam();
                queryParam1.getSqlMap().put("facilityMaintainSnapId", facilityMaintainSnap.getId() + "");
                List<MaintainOrderWorkContent> maintainOrderWorkContentList = maintainOrderWorkContentBiz.findList(queryParam1);
                if (CollectionUtils.isNotEmpty(maintainOrderWorkContentList)) {//查询单个工艺下的工作内容
                    for (MaintainOrderWorkContent maintainOrderWorkContent : maintainOrderWorkContentList) {
                        totalCount += 1;//每个运行场景下的都算入总数
                        if (StringUtils.isNotBlank(maintainOrderWorkContent.getResult())&&!maintainOrderWorkContent.getResult().equals("尚未选择")) {//不为空的都默认填写了，需要考虑默认值的情况,app在没有填写的单选项会传入一个尚未选择的字符，其实并未填写
                            finishCount += 1;
                        }
                        if (maintainOrderWorkContent.getAbnormal() != null && maintainOrderWorkContent.getAbnormal()) {//是否异常，false不是异常为正常，ture是异常，
                            flagSnap=true;
                        }
                        //查询有几个运行场景
                        JSONObject applicationJson = new JSONObject();
                        applicationJson.put("applicationName", maintainOrderWorkContent.getApplication_scenarios_name());
                        applicationJson.put("applicationId", maintainOrderWorkContent.getApplication_scenarios_id());
                        if (!applicationArray.contains(applicationJson)) {
                            applicationArray.add(applicationJson);
                        }

                    }
                    facilityMaintainSnap.setAbnormal(flagSnap);//全部都为正常才正常，一个为异常则这个设备都是异常
                }
                facilityMaintainSnapBiz.addOrUpdate(facilityMaintainSnap);

                //循环运行场景 如果单个运行场景的工作内容都是已完成 则认为该设备为已完成
                for (int i = 0; i < applicationArray.size(); i++) {
                    JSONObject json = applicationArray.getJSONObject(i);
                    Long applicationId = json.getLong("applicationId");
                    QueryParam queryParam2 = new QueryParam();
                    queryParam2.getSqlMap().put("facilityMaintainSnapId", facilityMaintainSnap.getId() + "");
                    queryParam2.getSqlMap().put("applicationId", applicationId + "");
                    List<MaintainOrderWorkContent> workContentList2 = maintainOrderWorkContentBiz.findList(queryParam2);
                    if (CollectionUtils.isNotEmpty(workContentList2)) {
                        boolean applicationCompleted = true;
                        for (MaintainOrderWorkContent workContent : workContentList2) {
                            if (StringUtils.isBlank(workContent.getResult())||workContent.getResult().equals("尚未选择")) {
                                applicationCompleted = false;
                                break;
                            } else {
                                //即使有结果内容 但如果强制拍照的没拍照 也算未完成
                                if (workContent.getPhoto() && (workContent.getContentPhoto() == null || workContent.getContentPhoto().size() == 0)) {
                                    applicationCompleted = false;
                                    break;
                                }
                            }
                        }
                        if (applicationCompleted) {
                            //只要其中一个循环内容全不为空，即设备其中一个应用场景已经全部完成 则认为该设备已完成
                            facilityMaintainSnap.setCompleted(true);
                            //同时认为该设备正常
//                            facilityMaintainSnap.setAbnormal(false);
                            facilityMaintainSnapBiz.addOrUpdate(facilityMaintainSnap);
                            break;
                        }
                    }
                }
            }
        }
        int percent = 0;
        if (totalCount != 0) {
            percent = (finishCount * 100) / totalCount;
        }
        maintainOrder.setPercent(percent);
        //查询工单是否异常
        boolean flag=false;
        for (FacilityMaintainSnap facilityMaintainSnap : facilityMaintainSnapList) {
            if (facilityMaintainSnap.isAbnormal()) {
                flag=true;
            }
        }
        maintainOrder.setAbnormal(flag);
        this.addOrUpdate(maintainOrder);
    }


    /**
     * 工单转单接口
     *
     * @param orderIds
     * @param userId
     * @return
     */
    public ResultDto setReceiver(String orderIds, String userId) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(userId));
        if (null == systemUser) {
            return ResultUtil.error("请选择指派的用户");
        }
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(orderIds);
        for (Object o : jsonArray) {
            MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(o));
            if (null == maintainOrder) {
                throw new RuntimeException("请选择正确的工单信息");
            }
            maintainOrder.setReceiveUser(systemUser);
            maintainOrder.setAssign(true);
            maintainOrder.setOrderStatusEnum(OrderStatusEnum.WAIT_PRESENCE);
            dao.update(maintainOrder);
            /*******添加工单日志********/
            maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.TRANSFER, request);


            //工时管理
            WorkingHours workingHours;
            QueryParam queryParam2 = new QueryParam();
            queryParam2.getSqlMap().put("partnerId", StringConverters.null2String(systemUser.getId()));
            queryParam2.getSqlMap().put("maintainOrderId", StringConverters.null2String(maintainOrder.getId()));
            List<WorkingHours> workingHoursList = workingHoursBiz.findList(queryParam2);
            if (CollectionUtil.isNotEmpty(workingHoursList)) {
                workingHours = workingHoursList.get(0);
            } else {
                workingHours = new WorkingHours();
                workingHours.setActualWorkingHours(0);
            }
            workingHours.setMaintainOrder(maintainOrder);
            workingHours.setWorkingHoursStatusEnum(WorkingHoursStatusEnum.STOP);
            workingHours.setPartner(systemUser);
            workingHours.setCharge(true);
            workingHours.setEnterprise(sessionEnterprise);
            workingHoursBiz.addOrUpdate(workingHours);

            //消息推送
            //消息推送
            String content = "维保单:" + maintainOrder.getOrderCode() + "被转单,请接单!";
            List<Long> ids = new ArrayList<>();
            ids.add(StringConverters.null2Long(userId));
            planMessageSendBiz.senMsg(maintainOrder.getId(), "maintain", maintainOrder.getEnterprise(), ids, content);
        }
        return ResultUtil.success();
    }


    public ResultDto getRemark(String contentId) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        JSONObject jsonObject = new JSONObject();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("contentId", contentId);
        List<WorkContentRemark> workContentRemarks = workContentRemarkBiz.findList(queryParam);
        if (CollectionUtil.isNotEmpty(workContentRemarks)) {
            WorkContentRemark workContentRemark = workContentRemarks.get(0);
            jsonObject = workContentRemark.toJSONObject();
        }
        return ResultUtil.success(jsonObject);
    }


    public ResultDto addRemark(String contentId, String question, String measure, String remark,Date createDate) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        WorkContentRemark workContentRemark;
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("contentId", contentId);
        List<WorkContentRemark> workContentRemarks = workContentRemarkBiz.findList(queryParam);
        if (CollectionUtil.isNotEmpty(workContentRemarks)) {
            workContentRemark = workContentRemarks.get(0);
        } else {
            workContentRemark = new WorkContentRemark();
            workContentRemark.setMaintainOrderWorkContent(maintainOrderWorkContentBiz.findModel(StringConverters.null2Long(contentId)));
        }
        if(createDate!=null){
            workContentRemark.setCreateDate(createDate);
        }
        workContentRemark.setQuestion(StringConverters.null2String(question));
        workContentRemark.setMeasure(StringConverters.null2String(measure));
        workContentRemark.setRemark(StringConverters.null2String(remark));
        workContentRemark.setEnterprise(sessionEnterprise);
        workContentRemarkBiz.addOrUpdate(workContentRemark);
        return ResultUtil.success();
    }

    /**
     * app保存工单接口
     *
     * @param request
     * @return
     */
    public ResultDto saveOrder(String name, String degree, String endTime, String required, String remindTime,
                               String assignUser, String assignPosition, String completeAuditId, String delayAuditId, String cancelAuditId,
                               String maintainData, HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (enterprise == null || systemUser == null) {
            return ResultUtil.error("登陆过期，请重新登陆");
        }

        List<Long> ids = new ArrayList<>();
        MaintainOrder maintainOrder = new MaintainOrder();
        String serial = StringConverters.getRandomString(10);
        maintainOrder.setEnterprise(enterprise);
        maintainOrder.setCreateUser(systemUser);
        maintainOrder.setSerial(serial);
        maintainOrder.setOrderCode(enterprise == null ? StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6) : enterprise.getId() + "-" + StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6));
        maintainOrder.setOrderName(name);
        maintainOrder.setDegree(degree);
        maintainOrder.setOrderType(true);
        maintainOrder.setStartDateTime(new Date());
        maintainOrder.setEndDateTime(StringConverters.formatDate(endTime, "yyyy-MM-dd HH:mm"));
        maintainOrder.setDelayRealTime(maintainOrder.getEndDateTime());
        maintainOrder.setRequired(required);
        maintainOrder.setRemindTime(StringConverters.null2Int(remindTime));
        maintainOrder.setRemindDateTime(StringConverters.beforeDate(maintainOrder.getStartDateTime(), maintainOrder.getRemindTime()));
        //指派数据
        net.sf.json.JSONArray userArray = net.sf.json.JSONArray.fromObject(assignUser);
        net.sf.json.JSONArray positionArray = net.sf.json.JSONArray.fromObject(assignPosition);
        if (userArray.size() != 0 && positionArray.size() != 0) {
            return ResultUtil.error("指派只能选择一种类型");
        } else if (userArray.size() != 0) {//指派人员
            maintainOrder.setOrderAssignTypeEnum(OrderAssignTypeEnum.USER);
            Set<SystemUser> systemUserSet = new HashSet<>();
            userArray.forEach(x -> {
                systemUserSet.add(systemUserBiz.findModel(StringConverters.null2Long(x)));
                ids.add(StringConverters.null2Long(x));
            });
            maintainOrder.setAssignUsers(systemUserSet);
            maintainOrder.setAssign(true);
        } else if (positionArray.size() != 0) {//指派岗位
            maintainOrder.setOrderAssignTypeEnum(OrderAssignTypeEnum.POSITION);
            Set<Position> positionHashSet = new HashSet<>();
            positionArray.forEach(x -> {
                positionHashSet.add(positionBiz.findModel(StringConverters.null2Long(x)));
                ids.add(StringConverters.null2Long(x));
            });
            maintainOrder.setAssign(true);
            maintainOrder.setAssignPositions(positionHashSet);
        }
        AuditFlow completeFlow = auditFlowBiz.findModel(StringConverters.null2Long(completeAuditId));//完成审批流
        if (completeFlow == null) {
            completeFlow = auditFlowBiz.getDefaultFlow("complete", enterprise, 2);
        }
        maintainOrder.setCompleteFlow(completeFlow != null ? completeFlow.getFlow() : "");
        maintainOrder.setAuditCompleteID(completeFlow != null ? completeFlow.getId() : null);

        AuditFlow delayFlow = auditFlowBiz.findModel(StringConverters.null2Long(delayAuditId));//延期审批流
        if (delayFlow == null) {
            delayFlow = auditFlowBiz.getDefaultFlow("delay", enterprise, 2);
        }
        maintainOrder.setDelayFlow(delayFlow != null ? delayFlow.getFlow() : "");
        maintainOrder.setDelayFlowID(delayFlow != null ? delayFlow.getId() : null);

        AuditFlow cancelFlow = auditFlowBiz.findModel(StringConverters.null2Long(cancelAuditId));//取消审批流
        if (cancelFlow == null) {
            cancelFlow = auditFlowBiz.getDefaultFlow("cancel", enterprise, 2);
        }
        maintainOrder.setCancelFlow(cancelFlow != null ? cancelFlow.getFlow() : "");
        maintainOrder.setCancelFlowID(cancelFlow != null ? cancelFlow.getId() : null);
        dao.add(maintainOrder);
        //设备工艺数据
        net.sf.json.JSONArray maintainArray = net.sf.json.JSONArray.fromObject(maintainData);
        if (maintainArray.size() == 0) {
            return ResultUtil.success("请添加设备");
        }
        maintainArray.forEach(x -> {
            String facilityId = net.sf.json.JSONObject.fromObject(x).getString("facilityId");
            String maintainId = net.sf.json.JSONObject.fromObject(x).getString("maintainId");
            facilityMaintainSnapBiz.saveFacilityMaintainSnap(maintainOrder.getId() + "", facilityId, maintainId, serial);

        });
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.CREATE_ORDER, request);//log日志

        //更新预计工时
        maintainOrder.setExpectWorkingHours(updateExpectWorkingHours(maintainOrder.getId() + ""));
        this.addOrUpdate(maintainOrder);

        //消息推送
        List<SystemUser> systemUsers1 = dao.maintainOrderUser(maintainOrder, enterprise, ids);
        String content = "有新的维保单!请接单";
        String takingAuthority = "ROLE_ENTERPRISE_MAINTAIN_ORDER_TAKING";
        for (SystemUser user : systemUsers1) {
            if (systemAuthorityBiz.hasAuthAuthority(takingAuthority, user.getId(), enterprise.getId())) {
                PlanMessageSend planMessageSend = new PlanMessageSend();
                planMessageSend.setContent(content);
                planMessageSend.setEnterprise(enterprise);
                planMessageSend.setSendDate(maintainOrder.getRemindDateTime());
                planMessageSend.setMessageTypeEnum(MessageTypeEnum.MAINTAIN);
                planMessageSend.setOrderCode(maintainOrder.getOrderCode());
                planMessageSend.setSendToUser(user);
                planMessageSendBiz.addOrUpdate(planMessageSend);
            }
        }


        return ResultUtil.success();

    }


    public ResultDto upload(MultipartFile file, String type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (file == null || StringUtils.isBlank(type)) {
            return ResultUtil.error("参数错误");
        }
        Resource resource = new Resource();
        String savePath = "";
        if ("img".equals(type)) {
            savePath = FileUtils.fileUpload(file, ConstantKeyFilePath.MAINTAIN_IMG_DIR, ConstantKeyFilePath.MAINTAIN_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            resource.setResourceName("维保图片");
            resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
        }
        resource.setPath(savePath);
        resource.setEnterprise(sessionEnterprise);
        resource.setCreateDate(new Date());
        resourceBiz.addOrUpdate(resource);
        return ResultUtil.success(resource.toJSONObject());
    }

    public ResultDto uploads(MultipartFile[] file, String type,String moduleType) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (file == null || StringUtils.isBlank(type)) {
            return ResultUtil.error("参数错误");
        }
        JSONArray jsonArray=new JSONArray();
        for(int i=0;i<file.length;i++){
            Resource resource = new Resource();
            String savePath = "";
            if ("img".equals(type)) {
                if(("maintain").equals(moduleType)){
                    savePath = FileUtils.fileUpload(file[i], ConstantKeyFilePath.MAINTAIN_IMG_DIR, ConstantKeyFilePath.MAINTAIN_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
                    resource.setResourceName("维保图片");
                }else{
                    savePath = FileUtils.fileUpload(file[i], ConstantKeyFilePath.REPAIR_IMG_DIR, ConstantKeyFilePath.REPAIR_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
                    resource.setResourceName("维保异常报修");
                }
                resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
                }else if ("mp3".equals(type)) {
                    savePath = FileUtils.fileUpload(file[i], ConstantKeyFilePath.REPAIR_MP3_DIR, ConstantKeyFilePath.REPAIR_MP3_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
                    resource.setResourceName("设备报修录音");
                    resource.setResourceTypeEnum(ResourceTypeEnum.MP3);
                }
            if(StringUtils.isEmpty(savePath)) {
                return ResultUtil.error();
            }
            resource.setPath(savePath);
            resource.setEnterprise(sessionEnterprise);
            resource.setCreateDate(new Date());
            resourceBiz.addOrUpdate(resource);
            jsonArray.add(resource.getId());
        }
        return ResultUtil.success(jsonArray);
    }

    /**
     * 工单终极审核  打分和评价接口
     *
     * @param orderId
     * @param score
     * @param remark
     * @return
     */
    public ResultDto finalAudit(String orderId, String score, String remark) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(orderId));
        if (null != maintainOrder) {
               /* int level = maintainOrder.getLevel();
                maintainOrder.setLevel(0);
                maintainOrder.setAuditing(false);//审核完结  置为初始
                maintainOrder.setPosition(null);
                maintainOrder.setAuditSystemUser(null);
                maintainOrder.setOrganization(null);
                maintainOrder.setAuditLast(false);
                maintainOrder.setAuditFirst(false);*/
            maintainOrder.setScore(StringConverters.null2Int(score));
            maintainOrder.setLastRemark(remark);
            if(maintainOrder.getOrderStatusEnum().getCode().equals("IN_AUDITING")){
                maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);
            }else if(maintainOrder.getDelay()){
                maintainOrder.setEndDateTime(maintainOrder.getDelayTime());
            }
            /*        maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);*/
            dao.update(maintainOrder);
            /*       *//*****添加审核日志*****//*
                auditOrderBiz.saveOrUpdate(maintainOrder, systemUser, true, remark, AuditTypeEnum.COMPLETE, level);
                //操作日志
                maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.AUDIT, request);*/
        }
        return ResultUtil.success();
    }

    /**
     * 批量审核接口
     *
     * @param orderIds
     * @param score
     * @param remark
     * @param systemUser
     * @param request
     * @return
     */
    public ResultDto batchAudit(String orderIds, String score, String remark, SystemUser systemUser, HttpServletRequest request) {
        JSONArray jsonArray = JSONArray.parseArray(orderIds);
        for (Object object : jsonArray) {
            MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(object));
            if (null != maintainOrder) {
//                if (maintainOrder.isAbnormal()) {
//                    throw new RuntimeException("工单号为：" + maintainOrder.getOrderCode() + "的工单异常，不可批量审核");
//                }
//                if (!maintainOrder.getOrderStatusEnum().getCode().equals("IN_AUDITING")) {
//                    throw new RuntimeException("工单号为：" + maintainOrder.getOrderCode() + "不可进行此操作");
//                }
                if (maintainOrder.isAuditLast()) {//工单终审状态
                    int level = maintainOrder.getLevel();
                    maintainOrder.setLevel(0);
                    maintainOrder.setAuditing(false);//审核完结  置为初始
                    maintainOrder.setPosition(null);
                    maintainOrder.setAuditSystemUser(null);
                    maintainOrder.setOrganization(null);
                    maintainOrder.setAuditLast(false);
                    maintainOrder.setAuditFirst(false);
                    maintainOrder.setScore(StringConverters.null2Int(score));
                    maintainOrder.setLastRemark(remark);
                    if(maintainOrder.getOrderStatusEnum().getCode().equals("IN_AUDITING")){
                        maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);
                    }else if(maintainOrder.getDelay()){
                        maintainOrder.setEndDateTime(maintainOrder.getDelayTime());
                    }
                    dao.update(maintainOrder);
                    /*****添加审核日志*****/
                    auditOrderBiz.saveOrUpdate(maintainOrder, systemUser, true, remark, AuditTypeEnum.COMPLETE, level);
                    //操作日志
                    maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.AUDIT, request);
                } else {//工单非终审状态
                    audit(maintainOrder.getId().toString(), "0", null, systemUser, request);
                }
            }
        }
        return ResultUtil.success();
    }

    public ResultDto partnerAddMore(String contentArray, String maintainOrderId) {
        JSONObject result = new JSONObject();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("maintainOrderId", maintainOrderId);
        JSONArray jsonArray = new JSONArray();
        List<FacilityMaintainSnap> list = facilityMaintainSnapBiz.findList(queryParam);

        List<String> hadList = new ArrayList<>();
        if (StringUtils.isNotBlank(contentArray)) {
            JSONArray array = JSONArray.parseArray(contentArray);
            for (int i = 0; i < array.size(); i++) {
                JSONObject j = array.getJSONObject(i);
                hadList.add(j.toString());
            }
        }

        for (FacilityMaintainSnap facilityMaintainSnap : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("facilityName", StringConverters.null2String(facilityMaintainSnap.getFacilityName()));
            jsonObject.put("facilityId", StringConverters.null2String(facilityMaintainSnap.getFacilityId()));
            jsonObject.put("snapId", StringConverters.null2String(facilityMaintainSnap.getId()));
            Set<MaintainOrderWorkContent> maintainOrderWorkContents = facilityMaintainSnap.getMaintainOrderWorkContents();
            JSONArray maintainArray = new JSONArray();
            for (MaintainOrderWorkContent maintainOrderWorkContent : maintainOrderWorkContents) {
                JSONObject maintainObject = new JSONObject();
                maintainObject.put("contentId", StringConverters.null2String(maintainOrderWorkContent.getId()));
                maintainObject.put("contentName", StringConverters.null2String(maintainOrderWorkContent.getName()));
                JSONObject hadObject = new JSONObject();
                hadObject.put("snapId", StringConverters.null2String(facilityMaintainSnap.getId()));
                hadObject.put("contentId", StringConverters.null2String(maintainOrderWorkContent.getId()));
                if (CollectionUtils.isNotEmpty(hadList) && hadList.contains(hadObject.toString())) {

                } else {
                    maintainArray.add(maintainObject);
                }
            }
            jsonObject.put("contentArray", maintainArray);
            if (maintainArray.size() > 0) {
                jsonArray.add(jsonObject);
            }
        }
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }

    public ResultDto addRepair(String maintainCode, String repairCode, String contentId) {
        MaintainToRepair maintainToRepair;
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("contentId", contentId);
        queryParam.getSqlMap().put("maintainCode", maintainCode);
        queryParam.getSqlMap().put("repairCode", repairCode);
        List<MaintainToRepair> list = maintainToRepairBiz.findList(queryParam);
        if (CollectionUtil.isNotEmpty(list)) {
            maintainToRepair = list.get(0);
        } else {
            maintainToRepair = new MaintainToRepair();
        }
        maintainToRepair.setMaintainCode(maintainCode);
        maintainToRepair.setRepairCode(repairCode);
        maintainToRepair.setContentId(StringConverters.null2Long(contentId));
        maintainToRepairBiz.addOrUpdate(maintainToRepair);
        return ResultUtil.success();
    }

    public ResultDto getDictSelect(String typeCode) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        return ResultUtil.success(dictInfoBiz.getDictSelect(sessionEnterprise, typeCode));
    }

    public ResultDto relateRepairOrder(String maintainCode) {
        JSONObject result = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("maintainCode", maintainCode);
        List<MaintainToRepair> list = maintainToRepairBiz.findList(queryParam);
        for (MaintainToRepair maintainToRepair : list) {
            jsonArray.add(maintainToRepair.getRepairCode());
        }
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }


    public List<SystemUser> submitOrderSendMsg(Organization organization, Position position, SystemUser systemUser, Enterprise enterprise) {
        return dao.submitOrderSendMsg(organization, position, systemUser, enterprise);
    }

    public JSONArray getHoursChartsData(String startDateTime, String endDateTime, String organizationIds,String enterpriseId) {
        JSONArray jsonArray = new JSONArray();

        List<Object> hoursChartsData = dao.getHoursChartsData(startDateTime, endDateTime, enterpriseId, organizationIds);
        for (Object data : hoursChartsData) {
            jsonArray.add(StringConverters.null2Int(data));
        }
        return jsonArray;
    }


    /**
     * 查看工作内容（设备和工艺）接口
     *
     * @param facilityId
     * @param maintainTechnologyId
     * @return
     */
    public ResultDto getFacilityAndTechnology(String facilityId, String maintainTechnologyId) {
        Facility facility = facilityBiz.findModel(StringConverters.ToLong(facilityId));
        MaintainTechnology maintainTechnology = maintainTechnologyBiz.findModel(StringConverters.ToLong(maintainTechnologyId));
        JSONObject result = new JSONObject();
        JSONObject data = new JSONObject();
        if (facility == null && maintainTechnology == null) {
            return ResultUtil.error("数据异常！");
        }
        JSONObject facilityJson = new JSONObject();
        if (facility != null) {
            facilityJson = facility.toDetailJSONObject();
            //设备专业名称
            facilityJson.put("rootCatName", "");
            if (facility.getFacilityCat() != null) {
                FacilityCat rootCat = facilityCatBiz.findRootCat(facility.getFacilityCat().getId());
                facilityJson.put("rootCatName", StringConverters.null2String(rootCat.getCatName()));
            }
        }
        JSONObject maintainTechnologyJson = new JSONObject();
        if (maintainTechnology != null) {
            maintainTechnologyJson = maintainTechnology.toJSONObject();
            JSONArray maintainDataArray = new JSONArray();
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("maintainTechnologyId", maintainTechnologyId);
            List<MaintainData> maintainDataList = maintainDataBiz.findList(queryParam);
            if (CollectionUtils.isNotEmpty(maintainDataList)) {
                for (MaintainData maintainData : maintainDataList) {
                    JSONObject maintainDataJson = maintainData.toJSONObject3();
                    maintainDataArray.add(maintainDataJson);
                }
            }
            maintainTechnologyJson.put("maintainData", maintainDataArray);
        }
        data.put("facility", facilityJson);
        data.put("maintainTechnology", maintainTechnologyJson);
        result.put("data", data);
        return ResultUtil.success(result);
    }

    /**
     * 计算预计工时
     */
    public long updateExpectWorkingHours(String maintainOrderId) {
        if (StringUtils.isBlank(maintainOrderId)) {
            return 0;
        }
        //更新预计工时
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("maintainOrderId", maintainOrderId);
        List<FacilityMaintainSnap> facilityMaintainSnapList = facilityMaintainSnapBiz.findList(queryParam);
        long expectWorkingHours = 0L;
        if (CollectionUtils.isNotEmpty(facilityMaintainSnapList)) {
            for (FacilityMaintainSnap facilityMaintainSnap : facilityMaintainSnapList) {
                if (facilityMaintainSnap != null) {
                    MaintainTechnology maintainTechnology = maintainTechnologyBiz.findModel(facilityMaintainSnap.getMaintainId());
                    if (maintainTechnology != null && StringUtils.isNotBlank(maintainTechnology.getEstimateTime())) {
                        long estimateTime = 0;
                        try {
                            estimateTime = Long.valueOf(maintainTechnology.getEstimateTime());
                        } catch (Exception e) {
                            logger.info("转long失败");
                        }
                        expectWorkingHours += estimateTime;
                    }
                }
            }
        }
        return expectWorkingHours;
    }

    public JSONObject countScore(String enterpriseId, String systemUserId) {
        JSONObject result = new JSONObject();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("systemUserId", systemUserId);
        List<Long> ids = new ArrayList<>();
        String idArray = com.useeinfo.framework.sugar.func.lang.StringUtils.strip(ids.toString(), "[]");
        List<Enterprise> enterprises = enterpriseBiz.findList(queryParam);
        for (Enterprise enterprise : enterprises) {
            ids.add(enterprise.getId());
        }
        List<String> list = new ArrayList<>();
        list.add("4");
        list.add("5");
        int score_0 = StringConverters.null2Int(dao.countScore("0", ids).get(0));
        int score_1 = StringConverters.null2Int(dao.countScore("1", ids).get(0));
        int score_2 = StringConverters.null2Int(dao.countScore("2", ids).get(0));
        int score_3 = StringConverters.null2Int(dao.countScore("3", ids).get(0));
        int score_4 = StringConverters.null2Int(dao.countScore("4", ids).get(0));
        int score_5 = StringConverters.null2Int(dao.countScore("5", ids).get(0));
        int totalScore = StringConverters.null2Int(dao.countScore("", ids).get(0));
        int score_achieve = StringConverters.null2Int(dao.countScore(StringUtils.strip(list.toString(), "[]"), ids).get(0));
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("num", score_5);
        jsonObject.put("name", "A");
        jsonObject.put("percent", DataHandleUtil.division(score_5, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_4);
        jsonObject.put("name", "B");
        jsonObject.put("percent", DataHandleUtil.division(score_4, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_3);
        jsonObject.put("name", "C");
        jsonObject.put("percent", DataHandleUtil.division(score_3, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_2);
        jsonObject.put("name", "D");
        jsonObject.put("percent", DataHandleUtil.division(score_2, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_1);
        jsonObject.put("name", "E");
        jsonObject.put("percent", DataHandleUtil.division(score_1, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_0);
        jsonObject.put("name", "F");
        jsonObject.put("percent", DataHandleUtil.division(score_0, totalScore));
        jsonArray.add(jsonObject);
        result.put("scores", jsonArray);
        result.put("totalNum", totalScore);
        result.put("achieve", DataHandleUtil.division(score_achieve, totalScore));
        return result;
    }

    /**
     * 正在维修中的设备
     *
     * @return
     */
    public JSONArray maintainFacilityCount(String enterpriseIds) {
        JSONArray rows = new JSONArray();
        if (StringUtils.isBlank(enterpriseIds)) {
            return rows;
        }
        List<Object[]> objects = dao.maintainFacilityCount(enterpriseIds);
        for (Object obj : objects) {
            Long facilityId = Long.parseLong(obj.toString());
            if (facilityId > 0) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("facilityId", facilityId + "");
                rows.add(jsonObject);
            }
        }
        return rows;
    }

    public JSONArray getTags(MaintainOrder maintainOrder, SystemUser systemUser, String status) {
        return dao.getTags(maintainOrder, systemUser, status);
    }

    /**
     * dashboard-获取分区响应时间-维保
     */
    public JSONArray getMaintainOrderResponseTime(Map<String, Object> dataMap) {
        JSONArray jsonArray = new JSONArray();
        List objects = dao.getMaintainOrderResponseTime(dataMap);
        if (CollectionUtils.isNotEmpty(objects)) {
            try {
                for (Object object : objects) {
                    net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(object);
                    jsonArray.add(AnalysisObjectList.getJsonString(j, 2));
                }
            } catch (Exception e) {
                logger.info("数据异常");
            }
        }
        return jsonArray;
    }
    public ResultDto nowWorkHours(String id){
        JSONObject jsonObject=new JSONObject();
        long totalHours = 0;
        MaintainOrder maintainOrder=dao.findModel(StringConverters.null2Long(id));
        if(maintainOrder==null){
            jsonObject.put("totalHours",totalHours);
            jsonObject.put("receiveHours",totalHours);
            return ResultUtil.success(jsonObject);
        }
        if(maintainOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")){
            totalHours=DateTimeUtils.getDistanceMinutes(maintainOrder.getPresenceTime(),new Date());
        }
        jsonObject.put("totalHours",maintainOrder.getTotalWorkingHours()+totalHours);
        jsonObject.put("receiveHours",maintainOrder.getWorkingHours()+totalHours);
        return ResultUtil.success(jsonObject);
    }

    //指定岗位信息
    public ResultDto getPosition(String pageIndex,String pageSize,Enterprise enterprise,String positionIds){

        QueryParam queryParam = new QueryParam(pageIndex,pageSize);
        String posHql = "select obj from Position obj where obj.deleteStatus is false and obj.enterprise.id="+enterprise.getId();
        if (!StringConverters.null2String(positionIds).equals("")) {
            String ids = "";
            for (Object object : JSONArray.parseArray(positionIds)) {
                if (ids.equals("")) {
                    ids = StringConverters.null2String(object);
                } else {
                    ids += "," + StringConverters.null2String(object);
                }
            }
            if (!StringConverters.null2String(ids).equals("")) {
                posHql += "  and obj.id not in(" + StringConverters.null2String(ids) + ")";
            }

        }
        JSONArray jsonArray = new JSONArray();
        for(Position position:positionBiz.hqlExcute(posHql,queryParam)){
            jsonArray.add(position.toJSONObject());
        }
        //String authorityName = Configuration.getConfigurationByName("maintainAuthorityName");
        return ResultUtil.success(jsonArray);
    }

    //指定人员信息
    public ResultDto getUser(String pageIndex,String pageSize,Enterprise enterprise,String userName,String userIds){

        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        String userHql = "select obj from SystemUser obj where obj.deleteStatus is false and obj.operationRole='common' and " +
                "exists( select er from obj.enterpriseSet er" +
                " where er.id=" + enterprise.getId() + ")";
        if (!StringConverters.null2String(userName).equals("")) {
            userHql += " and obj.userName like '%" + userName + "%'";
        }

        if (!StringConverters.null2String(userIds).equals("")) {
            String ids = "";
            for (Object object : JSONArray.parseArray(userIds)) {
                if (ids.equals("")) {
                    ids = StringConverters.null2String(object);
                } else {
                    ids += "," + StringConverters.null2String(object);
                }
            }
            if (!StringConverters.null2String(ids).equals("")) {
                userHql += "  and obj.id not in(" + StringConverters.null2String(ids) + ")";
            }

        }
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        for (SystemUser systemUser : systemUserBiz.hqlExcute(userHql, queryParam)) {
            jsonArray.add(systemUser.toJSONObject());
        }
        return ResultUtil.success(jsonArray);
    }

    //缓存内容
    public ResultDto cacheOrderInfo(String id,boolean type) {
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (sessionUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(id));
        if (null == maintainOrder) {
            return ResultUtil.error("该工单不存在");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误");
        }
        if (!maintainOrder.getOrderStatusEnum().getCode().equals("WAIT_PRESENCE") && !maintainOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")) {
            return ResultUtil.error("该状态下不能缓存");
        }
        if(!type){ //取消缓存功能
            maintainOrder.setCache(false);
            this.addOrUpdate(maintainOrder);
            return ResultUtil.success();
        }
        //1 基础数据
        JSONObject jsonObject = maintainOrder.toJSONObject();//基础信息

        //2工作流程
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONObject.fromObject(this.workProgress(id).getData().toString()).getJSONArray("rows");
        jsonObject.put("workProgress", jsonArray);
        //3工作日志,日志类型，重要程度
        jsonObject.put("workLogType",dictInfoBiz.getDictSelect(enterprise,"INSPECTION_WORK_LOG_CAT"));
        jsonObject.put("workLogLevel",dictInfoBiz.getDictSelect(enterprise,"INSPECTION_WORK_LOG_LEVEL"));
        //人员信息，岗位信息，用于巡检报修的指定人员和岗位
        jsonObject.put("assignUser",getUser("-1","-1",enterprise,null,"[]"));
        jsonObject.put("assignPosition",getPosition("-1","-1",enterprise,"[]"));

        //报修 紧急程度,需要判断是否与这个模块，有才能报修，没有则不能报修
        //获取该企业下配置的应用模块
        enterprise = enterpriseBiz.findModel(StringConverters.null2Long(SessionKeyUtils.getSessionEnterprise(request).getId()));
        QueryParam queryParamType = new QueryParam();
        queryParamType.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        queryParamType.getSqlMap().put("remark", "REPAIR");
        List<ApplicationModule> applicationModules=applicationModuleBiz.findList(queryParamType);
        if(CollectionUtils.isEmpty(applicationModules)){
            jsonObject.put("isRepair",false);
        }else{
            jsonObject.put("isRepair",true);
            QueryParam queryParam = new QueryParam(-1, -1);
            queryParam.setSqlOrder("order by id");
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
            jsonObject.put("repairLevel",repairLevelBiz.findJSONList(queryParam));//紧急程度
        }
        //4维保内容，包含设备工艺，pdf,备注
        JSONArray buttons = new JSONArray();
        JSONArray unfinished = new JSONArray();
        JSONArray finished = new JSONArray();
        QueryParam maintainParam = new QueryParam();
        maintainParam.getSqlMap().put("maintainOrderId", StringConverters.null2String(maintainOrder.getId()));
        List<FacilityMaintainSnap> FacilityMaintainSnaps = facilityMaintainSnapBiz.findList(maintainParam);
        //工时计算
        net.sf.json.JSONObject workingTime = net.sf.json.JSONObject.fromObject(nowWorkHours(id).getData());
        if (maintainOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")) {
            jsonObject.put("totalWorkingHours", workingTime.get("totalHours"));//总工时
            jsonObject.put("workingHours", workingTime.get("receiveHours"));//我的工时
        }
        //工作日志
        QueryParam logParam = new QueryParam(-1, -1);
        logParam.getSqlMap().put("maintainOrderId", id);
        jsonObject.put("workLog",maintainWorkLogBiz.findJSONList(logParam).getJSONArray("list"));
        //异常备注
        JSONArray remarkArray = new JSONArray();
        for (FacilityMaintainSnap facilityMaintainSnap : FacilityMaintainSnaps) {
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("facilityMaintainSnapId", StringConverters.null2String(facilityMaintainSnap.getId()));
            List<MaintainOrderWorkContent> maintainOrderWorkContents = maintainOrderWorkContentBiz.findList(queryParam);
            for (MaintainOrderWorkContent maintain : maintainOrderWorkContents) {
                //异常备注
                QueryParam contentParam = new QueryParam();
                contentParam.getSqlMap().put("contentId", StringConverters.null2String(maintain.getId()));
                //异常备注
                List<WorkContentRemark> maintainWorkContentRemarks = workContentRemarkBiz.findList(contentParam);
                if (CollectionUtils.isNotEmpty(maintainWorkContentRemarks)) {
                    for (WorkContentRemark remark : maintainWorkContentRemarks) {
                        remarkArray.add(remark.toJSONObject());
                    }
                }
            }

        }
        jsonObject.put("workRemark",remarkArray);
        //工艺设备信息
        for (FacilityMaintainSnap facilityMaintainSnap : FacilityMaintainSnaps) {
            JSONObject maintainObject = new JSONObject();
            Facility facility=facilityBiz.findModel(facilityMaintainSnap.getFacilityId());
            maintainObject.put("facilityName", StringConverters.null2String(facilityMaintainSnap.getFacilityName()));
            maintainObject.put("facilityCode", StringConverters.null2String(facilityMaintainSnap.getFacilityCode()));
            maintainObject.put("facilityId", facilityMaintainSnap.getFacilityId());
            maintainObject.put("applicationId", facilityMaintainSnap.getApplicationScenariosId() == null ? "" : facilityMaintainSnap.getApplicationScenariosId());
            maintainObject.put("maintainName", StringConverters.null2String(facilityMaintainSnap.getMaintainName()));
            maintainObject.put("spec", StringConverters.null2String(facilityMaintainSnap.getSpec()));
            maintainObject.put("QRCode", StringConverters.null2String(facility.getQrCode()));//二维码值
            maintainObject.put("facilityPosition", facility.getPosition()+ facility.getPrecisePosition()+facility.getDetailPosition());//二维码值
            maintainObject.put("areaId", facility.getArea()!=null?facility.getArea().getId():"");//区域id
            maintainObject.put("areaName", facility.getArea()!=null?facility.getArea().getAreaName():"");//二维码值
            FacilityCat facilityCat=facilityCatBiz.findModel(facility.getRootCatId());
            maintainObject.put("rootCatId", facilityCat!=null?facilityCat.getId():"");//报修专业id
            maintainObject.put("rootCatName", facilityCat!=null?facilityCat.getCatName():"");//报修专业名称
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("facilityMaintainSnapId", StringConverters.null2String(facilityMaintainSnap.getId()));
            List<MaintainOrderWorkContent> maintainOrderWorkContents = maintainOrderWorkContentBiz.findList(queryParam);
            JSONArray contentArray = new JSONArray();
            JSONArray applicationArray = new JSONArray();
            for (MaintainOrderWorkContent maintain : maintainOrderWorkContents) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("applicationName", maintain.getApplication_scenarios_name());
                jsonObject1.put("applicationId", maintain.getApplication_scenarios_id());
                if (!applicationArray.contains(jsonObject1)) {
                    applicationArray.add(jsonObject1);
                }
            }
            maintainObject.put("snapId", facilityMaintainSnap.getId());
            maintainObject.put("applicationArray", applicationArray);
            //设备详情信息
            for (MaintainOrderWorkContent maintain : maintainOrderWorkContents) {
                JSONObject contentObject = new JSONObject();
                contentObject.put("inputTypeEnum", StringConverters.null2String(maintain.getInputTypeEnum().getCode()));
                if ("COMPLETE_TYPE".equals(maintain.getInputTypeEnum().getCode()) || "STATUS_TYPE".equals(maintain.getInputTypeEnum().getCode())) {
                    String[] names = maintain.getInputTypeEnum().getName().split("、");
                    JSONArray nameArray = new JSONArray();
                    JSONObject nameS = new JSONObject();
                    nameS.put("content", "尚未选择");
                    nameS.put("isNormal", false);
                    nameArray.add(nameS);
                    for (String o : names) {
                        JSONObject nameStatus = new JSONObject();
                        if ("异常".equals(o) || "无此项目".equals(o) || "需处理（不能运转）".equals(o)) {
                            nameStatus.put("isNormal", false);
                        } else {
                            nameStatus.put("isNormal", true);
                        }
                        nameStatus.put("content", o);
                        nameArray.add(nameStatus);
                    }
//                    nameArray.addAll(Arrays.asList(names));
                    contentObject.put("inputType", nameArray);
                } else {
                    contentObject.put("inputType", StringConverters.null2String(maintain.getInputTypeEnum().getName()));
                }
                contentObject.put("contentId", StringConverters.null2Long(maintain.getId()));
                contentObject.put("unit", StringConverters.null2String(maintain.getUnit()));
                contentObject.put("applicationId", StringConverters.null2Long(maintain.getApplication_scenarios_id()));
                contentObject.put("applicationName", StringConverters.null2String(maintain.getApplication_scenarios_name()));
                contentObject.put("photo", StringConverters.null2Boolean(maintain.getPhoto()));
                contentObject.put("maxNumber", StringConverters.null2Double(maintain.getMaxNumber()));
                contentObject.put("minNumber", StringConverters.null2Double(maintain.getMinNumber()));
                contentObject.put("abnormal", StringConverters.null2Boolean(maintain.getAbnormal()));
                contentObject.put("name", StringConverters.null2String(maintain.getName()));
                contentObject.put("content", StringConverters.null2String(maintain.getContent()));
                JSONArray array = new JSONArray();
                if (StringUtils.isNotBlank(maintain.getContent())) {
                    array = JSONArray.parseArray(maintain.getContent());
                }
                contentObject.put("contentArray", array);
                contentObject.put("category", StringConverters.null2String(maintain.getCategory()));
                contentObject.put("result", StringConverters.null2String(maintain.getResult()));
                JSONArray photoArray = new JSONArray();
                if (maintain.getContentPhoto() != null) {
                    List<Resource> contentPhotos = new ArrayList<>(maintain.getContentPhoto());
                    contentPhotos.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
                    if (CollectionUtils.isNotEmpty(contentPhotos)) {
                        for (Resource resource : contentPhotos) {
                            photoArray.add(resource.getPath());
                        }
                    }
                }
                contentObject.put("photos", photoArray);
                String path = "";
                if (StringUtils.isNotBlank(maintain.getResourceIds())) {
                    Resource model = resourceBiz.findModel(StringConverters.null2Long(maintain.getResourceIds()));
                    if (model != null) {
                        path = model.getPath();
                    }
                }
                contentObject.put("resources", path);
                contentArray.add(contentObject);
            }
            maintainObject.put("contents", contentArray);
            if (facilityMaintainSnap.isCompleted()) {
                finished.add(maintainObject);
            } else {
                unfinished.add(maintainObject);
            }
        }
        //未完成设备，已完成设备
        jsonObject.put("finished", finished);
        jsonObject.put("unfinished", unfinished);

        //按钮，临时保存，提交，到场
        String takingAuthorityName = "ROLE_ENTERPRISE_MAINTAIN_ORDER_TAKING";
        if ("WAIT_PRESENCE".equals(maintainOrder.getOrderStatusEnum().getCode())) {
            if (systemAuthorityBiz.hasAuthAuthority(takingAuthorityName, sessionUser.getId(), enterprise.getId())) {
                buttons.add("presenceButton");
            }
        }else if  ("UNFINISHED".equals(maintainOrder.getOrderStatusEnum().getCode())) {
            buttons.add("saveButton");
            buttons.add("submitButton");
        }






        //参与人信息
        QueryParam partnerParam = new QueryParam();
        partnerParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        partnerParam.getSqlMap().put("maintainOrderId", StringConverters.null2String(maintainOrder.getId()));
        List<MaintainPartner> partners = maintainPartnerBiz.findList(partnerParam);
        JSONArray partnerArray = new JSONArray();
        for (MaintainPartner maintainPartner : partners) {
            JSONObject partnerObject = new JSONObject();
            partnerObject.put("deleteStatus", maintainPartner.isDeleteStatus());
            partnerObject.put("partnerId", maintainPartner.getId());
            partnerObject.put("userId", maintainPartner.getPartner().getId());
            partnerObject.put("userName", maintainPartner.getPartner().getUserName());
            partnerObject.put("workingHours", maintainPartner.getWorkingHours());
            partnerArray.add(partnerObject);
        }
        jsonObject.put("partner", partnerArray);
        jsonObject.put("buttons", buttons);
        jsonObject.put("systemUserId", sessionUser.getId());
        //更改字段
        maintainOrder.setCache(true);
        this.addOrUpdate(maintainOrder);
        //小标签
        JSONArray tags = new JSONArray();
        JSONObject tag;

        if (maintainOrder.isOrderType()) {
            tag = new JSONObject();
            tag.put("name", "一次性");
            tag.put("color", "blue");
            tags.add(tag);
        } else {
            tag = new JSONObject();
            tag.put("name", "周期性");
            tag.put("color", "blue");
            tags.add(tag);
        }
        if (null != maintainOrder.getOrderAssignTypeEnum()) {
            tag = new JSONObject();
            tag.put("name", "被指派");
            tag.put("color", "blue");
            tags.add(tag);
        }

        if (maintainOrder.getDelayRealTime() != null && maintainOrder.getDelayRealTime().before(new Date())) {
            tag = new JSONObject();
            tag.put("name", "逾期");
            tag.put("color", "blue");
            tags.add(tag);
        }
        if (maintainOrder.isAbnormal()) {
            tag = new JSONObject();
            tag.put("name", "异常");
            tag.put("color", "red");
            tags.add(tag);
        }
        if (maintainOrder.getDelay()) {
            tag = new JSONObject();
            tag.put("name", "延期");
            tag.put("color", "blue");
            tags.add(tag);
        }
        if (maintainOrder.getCancel()) {
            tag = new JSONObject();
            tag.put("name", "取消");
            tag.put("color", "blue");
            tags.add(tag);
        }
        jsonObject.put("tags", tags);

        return ResultUtil.success(jsonObject);
    }

    //保存缓存上传
    public ResultDto saveCacheOrder(String temporaryData, String maintainOrderId, String presenceDate, String presenceUser, String completeUser, String completeDate, String participantInputs,
                                    String workProgress,String workLog,String enterpriseId,String repairOrders,String workRemark) {
        Enterprise enterprise=enterpriseBiz.findModel(StringConverters.null2Long(enterpriseId));
        SystemUser systemUser=systemUserBiz.findModel(StringConverters.null2Long(completeUser));
        if(enterprise==null){
            return ResultUtil.error("session过期，请重新登录");
        }
        //保存基础数据 到场时间，到场人，完成时间，完成人
        MaintainOrder maintainOrder = dao.findModel(StringConverters.null2Long(maintainOrderId));
        if (maintainOrder.getPresenceTime() == null && StringConverters.ToDateTime(presenceDate) == null) {
            return ResultUtil.error("到场时间不能为空");
        }
        if (systemUserBiz.findModel(StringConverters.null2Long(presenceUser)) == null || systemUserBiz.findModel(StringConverters.null2Long(completeUser)) == null) {
            return ResultUtil.error("到场人和完场人不能为空");
        }
        if (maintainOrder.getFinishTime() == null && StringConverters.ToDateTime(completeDate) == null) {
            return ResultUtil.error("完成时间不能为空");
        }
        //离线缓存不允许重复上传
        if("COMPLETED".equals(maintainOrder.getOrderStatusEnum().getCode())||"IN_AUDITING".equals(maintainOrder.getOrderStatusEnum().getCode())){
            return ResultUtil.success();
        }
        maintainOrder.setPresence(true);
        maintainOrder.setPresenceUser(systemUserBiz.findModel(StringConverters.null2Long(presenceUser)));
        maintainOrder.setPresenceTime(StringConverters.ToDateTime(presenceDate));
        maintainOrder.setComplete(true);
        maintainOrder.setCompleteUser(systemUserBiz.findModel(StringConverters.null2Long(completeUser)));
        maintainOrder.setFinishTime(StringConverters.ToDateTime(completeDate));
        //1保存工时
        //负责人工时计算,工时累加
        long thisHours=DateTimeUtils.newGetDiffMinutesTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", DateTimeUtils.format(maintainOrder.getPresenceTime(), "yyyy-MM-dd HH:mm:ss")), StringConverters.ToDateTime(completeDate));
        maintainOrder.setWorkingHours(maintainOrder.getWorkingHours()+thisHours);
        //参与人工时计算，工时累加
        long totalWorkingHours=0;
        JSONArray participantInputsArray = JSON.parseArray(participantInputs);
        if (StringUtils.isNotBlank(participantInputs)&&participantInputsArray.size() > 0) {
            for (int i = 0; i < participantInputsArray.size(); i++) {
                JSONObject j = participantInputsArray.getJSONObject(i);
                Long partnerId = AliJsonObjectCover.ObjectLong(j, "userId");
                Long workingHours = AliJsonObjectCover.ObjectLong(j, "workingHours");
                QueryParam q = new QueryParam();
                q.getSqlMap().put("partnerId", partnerId == null ? "-1" : partnerId + "");
                q.getSqlMap().put("maintainOrderId", maintainOrder.getId() + "");
                q.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
                List<MaintainPartner> maintainPartnerList = maintainPartnerBiz.findList(q);
                if (CollectionUtils.isEmpty(maintainPartnerList)) {
                    return ResultUtil.error("参与人不存在！");
                }
                MaintainPartner maintainPartner = maintainPartnerList.get(0);
                totalWorkingHours+=workingHours;
                maintainPartner.setWorkingHours(maintainPartner.getWorkingHours() + workingHours);
                maintainPartner.setUpdateDate(StringConverters.ToDateTime(completeDate));
                maintainPartnerBiz.addOrUpdate(maintainPartner);
            }
        }
        maintainOrder.setTotalWorkingHours(thisHours+totalWorkingHours+maintainOrder.getTotalWorkingHours());
        this.addOrUpdate(maintainOrder);
        //2保存工作流程
        JSONArray workProgressArray = JSON.parseArray(workProgress);
        if(StringUtils.isNotBlank(workProgress)&&workProgressArray.size()>0){
            for (int i = 0; i < workProgressArray.size(); i++) {
                JSONObject jsonObject1=workProgressArray.getJSONObject(i);
                if(!StringUtils.isBlank(jsonObject1.getString("operationCode"))){
                    Date createDate=StringConverters.ToDateTime(jsonObject1.getString("createDate"));//时间取手机本地的时间
                    String id=jsonObject1.getString("id");
                    if(StringUtils.isEmpty(id)){
                        maintainOrderLogBiz.saveMaintainOrderLogByCache(maintainOrder, OrderOperationEnum.valueOf(jsonObject1.getString("operationCode")),systemUser,enterprise,createDate);
                    }
                }
            }
        }
        //3更新日志
        JSONArray workLogArray = JSON.parseArray(workLog);
        if(StringUtils.isNotBlank(workLog)&&workLogArray.size()>0){
            for (int i = 0; i < workLogArray.size(); i++) {
                JSONObject jsonObject1=workLogArray.getJSONObject(i);
                String typeId=jsonObject1.getString("workLogCatId");
                String levelId=jsonObject1.getString("workLogLevelId");
                Date createDate=StringConverters.ToDateTime(jsonObject1.getString("createDate"));
                String id=jsonObject1.getString("id");
                DictInfo typeInfo=dictInfoBiz.findModel(StringConverters.null2Long(typeId));
                DictInfo levelInfo=dictInfoBiz.findModel(StringConverters.null2Long(levelId));
                if(typeInfo==null){
                    return ResultUtil.error("日志类型不可为空");
                }
                if(levelInfo==null){
                    return ResultUtil.error("重要程度不可为空");
                }
                MaintainWorkLog maintainWorkLog;
                if(maintainOrderLogBiz.findModel(StringConverters.null2Long(id))!=null){
                    maintainWorkLog=maintainWorkLogBiz.findModel(StringConverters.null2Long(id));
                }else{
                    maintainWorkLog=new MaintainWorkLog();
                }
                maintainWorkLog.setSerial(CommonUtils.getRandomNumber(6));
                maintainWorkLog.setCode(maintainWorkLogBiz.getCode(StringConverters.null2String(enterprise.getId())));
                maintainWorkLog.setEnterprise(enterprise);
                maintainWorkLog.setLogLevel(levelInfo);
                maintainWorkLog.setLogCat(typeInfo);
                maintainWorkLog.setSystemUser(systemUser);
                maintainWorkLog.setContent(jsonObject1.getString("workContent"));
                maintainWorkLog.setMaintainOrder(maintainOrder);
                maintainWorkLog.setCreateDate(createDate);
                //上传日志照片,base64解密
                Set<Resource> resources=new HashSet<>();
                JSONArray logImgArray=jsonObject1.getJSONArray("photoPaths");
                if(StringUtils.isNotBlank(jsonObject1.getString("photoPaths"))&&logImgArray.size()>0){
                    logImgArray.forEach(x->{
                        Resource resource = resourceBiz.findModel(StringConverters.null2Long(x));
                        resource.setResourceName("工作日志图片");
                        resource.setEnterprise(enterprise);
                        resource.setCreateDate(createDate);
                        resourceBiz.addOrUpdate(resource);
                        resources.add(resource);
                    });
                }
                maintainWorkLog.setLogPhoto(resources);
                maintainWorkLogBiz.addOrUpdate(maintainWorkLog);
            }
        }


        //4保存异常报修工单
        JSONArray repairArray=JSONArray.parseArray(repairOrders);
        if(StringUtils.isNotBlank(repairOrders)&&repairArray.size()>0){
            for(int i=0;i<repairArray.size();i++){
                JSONObject jsonObject=repairArray.getJSONObject(i);
                String assignUser=jsonObject.getString("assignUser");
                String assignPosition=jsonObject.getString("assignPosition");
                String code=jsonObject.getString("code");
                String reportContent=jsonObject.getString("reportContent");
                String reportAddress=jsonObject.getString("reportAddress");
                String reportLevelId=jsonObject.getString("reportLevelId");
                String reportMajorId=jsonObject.getString("reportMajorId");
                Date reportDate=StringConverters.ToDateTime(jsonObject.getString("createDate"));
                String photoPaths=jsonObject.getString("photoPaths");
                String recordingPath=jsonObject.getString("recordingPath");
                //上传图片
                String type=jsonObject.getString("type");
                String areaId=jsonObject.getString("areaId");
                String facilityPosition=jsonObject.getString("facilityPosition");
                ResultDto dto=repairOrderBiz.addRepair(assignUser,assignPosition,code,reportContent,reportAddress,reportLevelId,reportMajorId,photoPaths,recordingPath,type,areaId,facilityPosition,systemUser,enterprise,reportDate);
                String reportCode= "";
                if(dto != null && dto.getData() != null) {
                    // 规避空指针
                    reportCode= net.sf.json.JSONObject.fromObject(dto.getData()).getString("code");
                }
                this.addRepair(maintainOrder.getOrderCode(), reportCode,maintainOrderId);
            }
        }


        //5更新巡检内容  包括工艺信息，照片，异常备注
        JSONArray jsonArray = JSONArray.parseArray(temporaryData);
        List<String> facilityMaintainSnapIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(temporaryData)&&jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String facilityMaintainSnapId = jsonObject.getString("facilityMaintainSnapId");//巡检设备ID
                String maintainOrderWorkContentId = jsonObject.getString("maintainOrderWorkContentId");//巡检内容ID
                String result = jsonObject.getString("result");//输入内容
                JSONArray photoArray = jsonObject.getJSONArray("photoPath");//照片路径
                String abnormal = jsonObject.getString("abnormal");//是否异常，true为异常，false正常
                //保存该设备下的当前应用场景
                Long applicationId = StringConverters.ToLong(jsonObject.getString("applicationId"));//当前的应用场景ID
                FacilityMaintainSnap facilityMaintainSnap = facilityMaintainSnapBiz.findModel(StringConverters.ToLong(facilityMaintainSnapId));
                if(facilityMaintainSnap!=null){
                    facilityMaintainSnap.setApplicationScenariosId(applicationId);
                    facilityMaintainSnapBiz.addOrUpdate(facilityMaintainSnap);
                }

                if (!facilityMaintainSnapIds.contains(facilityMaintainSnapId)) {
                    facilityMaintainSnapIds.add(facilityMaintainSnapId);
                }
                MaintainOrderWorkContent maintainOrderWorkContent = maintainOrderWorkContentBiz.findModel(StringConverters.ToLong(maintainOrderWorkContentId));
                if (maintainOrderWorkContent == null) {
                    continue;
                }
                maintainOrderWorkContent.setResult(result);
                maintainOrderWorkContent.setContentPhoto(null);
                if (StringUtils.isNotBlank(abnormal)) {
                    maintainOrderWorkContent.setAbnormal(Boolean.parseBoolean(abnormal));
                }
                if (photoArray != null && photoArray.size() > 0) {
                    Set<Resource> set = new HashSet<>();
                    for (Object object : photoArray) {
                        Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
                        resource.setEnterprise(enterprise);
                        resource.setResourceName("巡检照片");
                        resourceBiz.addOrUpdate(resource);
                        set.add(resource);
                    }
                    maintainOrderWorkContent.setContentPhoto(set);
                }
                if (StringUtils.isNotBlank(result) || photoArray != null) {
                    maintainOrderWorkContent.setFinishTime(StringConverters.ToDateTime(completeDate));
                }
                maintainOrderWorkContentBiz.addOrUpdate(maintainOrderWorkContent);
            }
        }
        //异常备注
        JSONArray remarkArray=JSONArray.parseArray(workRemark);
        if (remarkArray != null && remarkArray.size() > 0) {
            for (int j = 0; j < remarkArray.size(); j++) {
                JSONObject remarkObject=remarkArray.getJSONObject(j);
                String contentId=remarkObject.getString("contentId");
                String question=remarkObject.getString("question");
                String measure=remarkObject.getString("measure");
                String remark=remarkObject.getString("remark");
                String createDate=remarkObject.getString("createDate");
                this.addRemark(contentId,question,measure,remark,StringConverters.ToDateTime(createDate));
            }
        }
        //更新百分比(以及工单是否异常 以及更新maintainOrder表工时字段)
        this.updatePercent(maintainOrderId);

        //查询审批信息，并且推送
        List<Long> ids = new ArrayList<>();
        if (maintainOrder.getAuditCompleteID() != null) {
            JSONArray completeArray = JSONArray.parseArray(maintainOrder.getCompleteFlow());
            if (completeArray != null && completeArray.size() > 0) {
                maintainOrder.setOrderStatusEnum(OrderStatusEnum.IN_AUDITING);
                maintainOrder.setLevel(1);
                if (completeArray.size() == 1) {
                    maintainOrder.setAuditLast(true);
                } else {
                    maintainOrder.setAuditFirst(true);
                }
                maintainOrder.setAuditing(true);
                JSONObject jsonObject = completeArray.getJSONObject(0);
                Long organizationId = jsonObject.getLong("organizationId");
                Organization organization = organizationBiz.findModel(organizationId);
                maintainOrder.setOrganization(organization);
                String nodeTypeEnum = jsonObject.getString("nodeTypeEnum");
                Long relationId = jsonObject.getLong("relationId");
                if (nodeTypeEnum.equals("USER")) {
                    SystemUser user = systemUserBiz.findModel(relationId);
                    maintainOrder.setAuditSystemUser(user);
                    ids.add(user.getId());
                } else {
                    Position position = positionBiz.findModel(relationId);
                    maintainOrder.setPosition(position);
                    ids.addAll(systemUserBiz.getUserIdsByPosition(relationId.toString(),organizationId.toString(),enterprise.getId()+""));
                }
                ids.add(maintainOrder.getReceiveUser().getId());//工单人也需要消息推送

                //消息推送
                String content = "巡检单:" + maintainOrder.getOrderCode() + "已完成,等待审核!";
                planMessageSendBiz.senMsg(maintainOrder.getId(),"maintain",maintainOrder.getEnterprise(),ids,content);
            } else {
                maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);
            }

        } else {
            maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);
        }
        maintainOrder.setPercent(100);
        this.addOrUpdate(maintainOrder);
        return ResultUtil.success("维保单："+maintainOrder.getOrderCode()+"上传成功");


    }

    /**
     * Dashboard 维保总数统计
     * @param sqlMap 参数
     * @return Long
     */
    public Long totalRecordToDashboard(Map<String, String> sqlMap) {
        Long aLong = dao.totalRecordToDashboard(sqlMap);
        return aLong;
    }
}
